poj 3278

来源:互联网 发布:淘宝如何提高搜索排名 编辑:程序博客网 时间:2024/06/06 08:27

这个题要注意边界,例如边界为0,边界超出的100000也不要进队列,否则可能导致数组越界

#include<iostream>#include<queue>#include<cstring>using namespace std;int n,k;struct point{int x;int step;};queue<point> q;bool vis[200020];void bfs(int x){point tmp,hd;tmp.x=x;tmp.step=0;vis[x]=1;q.push(tmp);while(!q.empty()){hd=q.front();if(hd.x==k){cout<<hd.step<<endl;return ;}q.pop();if(!vis[2*hd.x]&&2*hd.x<100005)//一开始没加100005,数组越界了{tmp.x=2*hd.x;tmp.step=hd.step+1;q.push(tmp);vis[2*hd.x]=1;}if(hd.x>0&&vis[hd.x-1]==0){tmp.x=hd.x-1;tmp.step=hd.step+1;q.push(tmp);vis[hd.x-1]=1;}if(!vis[hd.x+1]&&hd.x+1<100005){tmp.x=hd.x+1;tmp.step=hd.step+1;q.push(tmp);vis[hd.x+1]=1;}}}int main(){cin>>n>>k;memset(vis,0,sizeof(vis));bfs(n);}


0 0
原创粉丝点击