poj 3278——Catch That Cow
2015-01-30 10:21
148 查看
题意:每次操作可以使一个数加一减一或者乘2,求一个数变成另一个数最少要操作几次
思路:bfs
错误:当k小于n的时候,可以直接用n-k就是结果。但是不知道为什么不用这个特殊处理就re了
代码如下:
思路:bfs
错误:当k小于n的时候,可以直接用n-k就是结果。但是不知道为什么不用这个特殊处理就re了
代码如下:
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; int abs(int x){ return x<0?-x:x; } int dis[300005]; int n,k; void bfs() { queue<int> q; q.push(n); dis =0; while(!q.empty()){ int tmp=q.front(); q.pop(); if((abs(n-k)>abs(tmp+1-k)||tmp+1<=k)&&(dis[tmp+1]==-1||dis[tmp+1]>dis[tmp]+1)){ dis[tmp+1]=dis[tmp]+1; q.push(tmp+1); } if((abs(n-k)>abs(tmp-1-k)||tmp-1<=k&&tmp-1>=0)&&(dis[tmp-1]==-1||dis[tmp-1]>dis[tmp]+1)){ dis[tmp-1]=dis[tmp]+1; q.push(tmp-1); } if(abs(n-k)>abs(tmp*2-k)&&tmp!=0&&(dis[tmp*2]==-1||dis[tmp*2]>dis[tmp]+1)){ dis[tmp*2]=dis[tmp]+1; q.push(tmp*2); } } } int main() { scanf("%d%d",&n,&k); memset(dis,-1,sizeof(dis)); if(k<=n){ printf("%d\n",n-k); return 0; } bfs(); printf("%d\n",dis[k]); return 0; }
相关文章推荐
- POJ 3278 Catch That Cow[BFS]
- 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
- Catch That Cow POJ - 3278
- poj 3278 Catch That Cow
- POJ 3278 Catch That Cow <BFS>
- poj-3278-Catch That Cow
- Catch That Cow POJ - 3278 图论模型 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
- poj 3278 Catch that cow(BFS 广搜)