【POJ3278】Catch That Cow

一时失言乱红尘 2022-09-24 11:25 272阅读 0赞

这里写图片描述
这里写图片描述

搜索里应用型的题目。
记得考虑临界情况哦。
BFS代码:

  1. #include<stdio.h>
  2. #include<queue>
  3. #include<string.h>
  4. #include<algorithm>
  5. using namespace std;
  6. const int N = 100000;
  7. bool vis[N+100];
  8. int n,m;
  9. struct note {
  10. int t;
  11. int id;
  12. } s;
  13. bool check(int a) {
  14. if(a<0||a>N||vis[a])
  15. return 0;
  16. return 1;
  17. }
  18. int bfs(int n,int m) {
  19. queue<note >Q;
  20. s.t=n,s.id=0;
  21. Q.push(s);
  22. vis[s.t]=true;
  23. while(!Q.empty()) {
  24. note now,end;
  25. now=Q.front();
  26. Q.pop();
  27. if(now.t==m) {
  28. return now.id;
  29. }
  30. end.t=now.t+1;
  31. if(check(end.t)) {
  32. end.id=now.id+1;
  33. Q.push(end);
  34. vis[end.t]=true;
  35. }
  36. end.t=now.t-1;
  37. if(check(end.t)) {
  38. end.id=now.id+1;
  39. Q.push(end);
  40. vis[end.t]=true;
  41. }
  42. end.t=now.t*2;
  43. if(check(end.t)) {
  44. end.id=now.id+1;
  45. Q.push(end);
  46. vis[end.t]=true;
  47. }
  48. }
  49. return -1;
  50. }
  51. int main() {
  52. while(scanf("%d%d",&n,&m)!=EOF) {
  53. memset(vis,false,sizeof(vis));
  54. int ans=bfs(n,m);
  55. printf("%d\n",ans);
  56. }
  57. return 0;
  58. }

http://poj.org/problem?id=3278

发表评论

表情:
评论列表 (有 0 条评论,272人围观)

还没有评论,来说两句吧...

相关阅读