POJ 3278 Catch That Cow
2012-09-28 16:49
253 查看
题目链接:http://poj.org/problem?id=3278
思路:BFS
注意:老是错误,才发现是队列没有清空
总结:自己写的代码很烂的,由于是用队列,我想的法子是把每一次(每一步)队列中的数据缓存到数组解决问题,而大神都是...
代码如下:
于是在网上参考了别人的代码,自己再写了一遍ac了,发现大神是用数组的下标代表每一步跳到的值,而用数组的值代表从n(起始值)跳到数组下标所用过的步数
代码如下
看着后面的代码,比纯自己写的赏心悦目多了,看来代码能力还带弱了,加油
思路:BFS
注意:老是错误,才发现是队列没有清空
总结:自己写的代码很烂的,由于是用队列,我想的法子是把每一次(每一步)队列中的数据缓存到数组解决问题,而大神都是...
代码如下:
#include<iostream> #include<string.h> #include<stdio.h> #include<queue> #include<algorithm> #define MAX 2000001 using namespace std; bool b[MAX]; int temps[MAX]; int count_t,k,n; queue<int>q; void bfs() { if(n==k) return ; q.push(n-1); q.push(n+1); q.push(n*2); b =false; b[n-1]=false; b[n+1]=false; b[n*2]=false; count_t++; while(!q.empty()) { int times=0; while(!q.empty()) { temps[times]=q.front(); q.pop(); times++; } count_t++; while(times--) { int temp=temps[times]; if(temp==k) return ; if(b[temp-1]&&temp-1>=0) { q.push(temp-1); b[temp-1]=false; } if(b[temp+1]) { q.push(temp+1); b[temp+1]=false; } if(b[temp*2]&&temp*2<200001) { q.push(temp*2); b[temp*2]=false; } } } } int main() { while(scanf("%d %d",&n,&k)!=EOF&&n!=-1&&k!=-1) { memset(b,true,sizeof(b)); count_t=0; if(n==k) { printf("0\n"); continue; } bfs(); printf("%d\n",count_t-1); while(!q.empty()) { q.pop(); } } return 0; }
于是在网上参考了别人的代码,自己再写了一遍ac了,发现大神是用数组的下标代表每一步跳到的值,而用数组的值代表从n(起始值)跳到数组下标所用过的步数
代码如下
#include<stdio.h> #include<algorithm> #include<queue> #include<iostream> #include<string.h> #define MAX 100001 using namespace std; bool visit[MAX]; int step[MAX]; queue<int >q; int bfs(int n,int k) { visit =false; q.push(n); step =0; int i,next; while(!q.empty()) { int head=q.front(); q.pop(); if(head==k) return step[head]; for(i=0;i<3;i++) { if(i==0) next=head-1; if(i==1) next=head+1; if(i==2) next=head*2; if(next<0||next>MAX) continue; if(visit[next]) { q.push(next); visit[next]=false; step[next]=step[head]+1; } } } } int main() { int n,k; while(~scanf("%d%d",&n,&k)) { memset(visit,true,sizeof(visit)); cout<<bfs(n,k)<<endl; while(!q.empty()) { q.pop(); } } return 0; }
看着后面的代码,比纯自己写的赏心悦目多了,看来代码能力还带弱了,加油
相关文章推荐
- poj 3278 Catch That Cow
- POJ 3278-Catch That Cow
- POJ 3278 Catch That Cow
- POJ-3278 Catch That Cow 解题报告
- poj 3278 Catch That Cow 优化深搜
- POJ-3278-Catch That Cow
- POJ 3278 Catch That Cow (BFS)
- poj 3278 Catch That Cow bfs
- POJ 3278:Catch That Cow 抓住那头牛
- POJ 3278 Catch That Cow(模板——BFS)
- poj 3278 Catch That Cow
- POJ - 3278 Catch That Cow
- poj 3278(hdu 2717) Catch That Cow(bfs)
- POJ 3278 Catch That Cow
- poj 3278 Catch That Cow 广搜
- poj 3278 Catch That Cow
- poj 3278 Catch That Cow(bfs)
- POJ-3278 Catch That Cow (BFS入门题
- POJ - 3278 Catch That Cow (BFS)
- POJ 3278 Catch that cow