Catch That Cow POJ - 3278
考察:bfs
稍微思考一下就知道dfs会超时,但是这道题我还花了很多时间仔细思考了第一次达到新的点是不是最短时间
动笔才是王道啊!!!
易错:
我写的判断条件是超出k的两倍就不考虑此点,实际上k可能比n小,这样会WA
1 #include <iostream> 2 #include <queue> 3 #include <cstring> 4 using namespace std; 5 const int N = 200010; 6 int n,k,dist[N],xx[3] = {-1,1,2000}; 7 int bfs() 8 { 9 queue<int> q; 10 q.push(n); 11 memset(dist,-1,sizeof(dist)); 12 dist[n] = 0; 13 int maxn = max(n,k); 14 while(!q.empty()) 15 { 16 int x = q.front(); 17 q.pop(); 18 int d = dist[x]; 19 if(x==k) return d; 20 for(int i=0;i<3;i++){ 21 int dx = x+xx[i]; 22 if(dx-x==2000) dx = x*2; 23 if(dx>=0&&dx<=2*maxn&&dist[dx]==-1) 24 { 25 dist[dx] = d+1; 26 q.push(dx); 27 } 28 } 29 } 30 return -1; 31 } 32 int main() 33 { 34 scanf("%d%d",&n,&k); 35 printf("%d\n",bfs()); 36 return 0; 37 }