bfs poj-3278
阿新 • • 發佈:2021-07-05
題目:
https://vjudge.net/problem/POJ-3278
思路:
bfs
我用標記判斷的時候,注意n==k的情況下
或者直接在While 迴圈裡把if(x==k)
{return d[k];
}
#include<stdio.h> #include<queue> using namespace std; const int maxn=1e5+8; int v[maxn]={0}; int d[maxn]={0}; int n,k; void bfs(int n) { d[n]=0; v[n]=1; queue<int> q; q.push(n);while(!q.empty()) { int x=q.front(); q.pop(); int t; t=x-1; if(t>=0&&t<=100000&&!v[t]) { v[t]=1; d[t]=d[x]+1; q.push(t); } t=x+1; if(t>=0&&t<=100000&&!v[t]) { v[t]=1; d[t]=d[x]+1; q.push(t); } t=2*x; if(t>=0&&t<=100000&&!v[t]) { v[t]=1; d[t]=d[x]+1; q.push(t); } } if(d[k]) { printf("%d\n",d[k]); return; } } int main() { scanf("%d %d",&n,&k); if(n==k) printf("0\n"); else if(n>k) printf("%d\n",n-k); else bfs(n); }