[关闭]
@lychee123 2017-04-16T10:28:07.000000Z 字数 1032 阅读 938

Catch That Cow(一条直线上的bfs)

BFS


题面链接

  1. #include<stdio.h>
  2. #include<algorithm>
  3. #include<string>
  4. #include<string.h>
  5. #include<queue>
  6. using namespace std;
  7. int vis[200010];
  8. int n,k,i,j,ans;
  9. struct node
  10. {
  11. int x,time;
  12. };
  13. int bfs(int x,int y)
  14. {
  15. node now,next;
  16. queue<node>q;
  17. now.x=x;
  18. now.time=0;
  19. q.push(now);
  20. memset(vis,0,sizeof(vis));
  21. vis[x]=1;
  22. while(!q.empty())
  23. {
  24. now=q.front();
  25. q.pop();
  26. if(now.x==y)
  27. return now.time;
  28. next.x=now.x+1;
  29. if(next.x>=0&&next.x<=max(n,k)*2&&vis[next.x]==0)
  30. {
  31. next.time=now.time+1;
  32. vis[next.x]=1;
  33. q.push(next);
  34. }
  35. next.x=now.x-1;
  36. if(next.x>=0&&next.x<max(n,k)*2&&vis[next.x]==0)
  37. {
  38. next.time=now.time+1;
  39. vis[next.x]=1;
  40. q.push(next);
  41. }
  42. next.x=now.x*2;
  43. if(next.x>=0&&next.x<max(n,k)*2&&vis[next.x]==0)
  44. {
  45. next.time=now.time+1;
  46. vis[next.x]=1;
  47. q.push(next);
  48. }
  49. }
  50. return -1;
  51. }
  52. int main()
  53. {
  54. while(~scanf("%d%d",&n,&k))
  55. {
  56. int num=bfs(n,k);
  57. printf("%d\n",num);
  58. }
  59. return 0;
  60. }
ps:最开始当n>k时这种情况的数据过不了,所以加了特判过的,但最后才找到问题,就是n,k取max那里,之前直接写的2*k。
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注