标签:
5 17
4HintThe fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
//BFS
#include<cstdio> #include<queue> #include<cstring> #define INF 0xfffffff #define max 100000 using namespace std; bool vis[max+100]; int min_time; int tar; struct cow { int start,time; }a,temp; void BFS(int st) { queue<cow>q; a.start=st; a.time=0; memset(vis,0,sizeof(vis)); vis[a.start]=1; q.push(a); while(!q.empty()) { a=q.front(); q.pop(); for(int i=1;i<=3;++i) { if(i==1) temp.start=a.start+1; else if(i==2) temp.start=a.start-1; else if(i==3) temp.start=a.start*2; temp.time=a.time+1; if(temp.start==tar) { if(min_time>temp.time) min_time=temp.time; } if(temp.start>max||temp.start<0) continue; if(!vis[temp.start]) { vis[temp.start]=1; q.push(temp); } } } } int main() { int st; while(~scanf("%d%d",&st,&tar)) { if(st==tar) { printf("0\n"); continue; } if(st>tar) { printf("%d\n",st-tar); continue; } min_time=INF; BFS(st); printf("%d\n",min_time); } return 0; }
#include<cstdio> #include<queue> #include<cstring> #define INF 0xfffffff #define max 100000 using namespace std; bool vis[max+100]; int min_time; int tar; struct cow { int start,time; friend bool operator <(cow a,cow b) { return a.time>b.time; } }a,temp; void BFS(int st) { priority_queue<cow>q; a.start=st; a.time=0; memset(vis,0,sizeof(vis)); vis[a.start]=1; q.push(a); while(!q.empty()) { a=q.top(); q.pop(); for(int i=1;i<=3;++i) { if(i==1) temp.start=a.start+1; else if(i==2) temp.start=a.start-1; else if(i==3) temp.start=a.start*2; temp.time=a.time+1; if(temp.start==tar) { min_time=temp.time; return ; } if(temp.start>max||temp.start<0) continue; if(!vis[temp.start]) { vis[temp.start]=1; q.push(temp); } } } } int main() { int st; while(~scanf("%d%d",&st,&tar)) { if(st==tar) { printf("0\n"); continue; } if(st>tar) { printf("%d\n",st-tar); continue; } min_time=INF; BFS(st); printf("%d\n",min_time); } return 0; }
我总结一下什么时候用BFS,什么时候用DFS,有有限边界的,比如给了一个图,就用DFS方便,如果边界太大1000000,就用BFS
不然会爆,因为运行太多1000000次出不来,这个程序想都不用想就不行。然而好像BFS是万能的。暂时还没找到不能用的情况,可能做的题目太少了吧
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/yuzhiwei1995/article/details/47312941