标签:
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9276 Accepted Submission(s):
2907
#include<stdio.h> #include<string.h> #include<queue> #define MAX 1000100 using namespace std; int n,m; int vis[MAX]; struct node { int x; int step; friend bool operator < (node a,node b) { return a.step>b.step; } }; int judge(int x) { if(x < 0||x > MAX||vis[x]) return 0; return 1; } void bfs(int n,int k) { int i,j; priority_queue<node>q; node beg,end; beg.x=n; beg.step=0; q.push(beg); vis[n]=1; while(!q.empty()) { beg=q.top(); q.pop(); if(beg.x==k) { printf("%d\n",beg.step); return ; } end.x=beg.x-1; if(judge(end.x)) { vis[end.x]=1; end.step=beg.step+1; q.push(end); } end.x=beg.x+1; if(judge(end.x)) { vis[end.x]=1; end.step=beg.step+1; q.push(end); } end.x=beg.x*2; if(judge(end.x)) { vis[end.x]=1; end.step=beg.step+1; q.push(end); } } } int main() { int i; while(scanf("%d%d",&n,&m)!=EOF) { memset(vis,0,sizeof(vis)); bfs(n,m); } return 0; }
标签:
原文地址:http://www.cnblogs.com/tonghao/p/4707022.html