ACM暑期集训——专题一[BFS]

来源:互联网 发布:cds测试软件7.1 编辑:程序博客网 时间:2024/06/05 04:12
#include <iostream>#include <stdio.h>#include <queue>using namespace std;struct node{int x,step;};queue<node> Q;int v[200500];int k;void bfs(){int x,step;while(!Q.empty()){node tmp=Q.front();Q.pop();x=tmp.x;step=tmp.step;if(x==k){printf("%d\n",step);}if(x>=1&&v[x-1]==0){node t;v[x-1]=1;t.x=x-1;t.step=step+1;Q.push(t);}if(x<=k&&v[x+1]==0){node t;v[x+1]=1;t.x=x+1;t.step=step+1;Q.push(t);}if(x<=k&&v[x*2]==0){node t;v[x*2]=1;t.x=x*2;t.step=step+1;Q.push(t);}}}int main(){int n;while(scanf("%d %d",&n,&k)!=EOF){node begin;v[n]=1;begin.x=n;begin.step=0;Q.push(begin);bfs();}return 0;}


0 0
原创粉丝点击