首页 > 代码库 > hdu 3278
hdu 3278
#include <iostream>#include <queue>#include <stdio.h>#include <string>using namespace std;int a,b,used[200020];queue<int>q;int ok(int n){ if(n < 200000&&n >= 0&&used[n]==0) return 1; return 0; } void bfs(){ int n; while(!q.empty()) { // cout<<q.front()<<endl; if(q.front() == b) return ; n = q.front() - 1; if(ok(n)){used[n] = used[q.front()]+1;q.push(n);} n = q.front() + 1; if(ok(n)){used[n] = used[q.front()]+1;q.push(n); } n = q.front()*2; if(ok(n)){used[n] = used[q.front()]+1;q.push(n); } q.pop(); } } int main() { while(cin>>a>>b) { memset(used,0,sizeof(used)); q.push(a); used[a] = 1; bfs(); cout<<used[b]-1<<endl; while(!q.empty()) { q.pop(); } } return 0; }
#include <iostream>
#include <queue>
#include <stdio.h>
#include <string>
using namespace std;
int a,b,used[200020];
queue<int>q;
int ok(int n)
{
if(n < 200000&&n >= 0&&used[n]==0) return 1;
return 0;
}
void bfs()
{ int n;
while(!q.empty())
{
// cout<<q.front()<<endl;
if(q.front() == b) return ;
n = q.front() - 1;
if(ok(n)){used[n] = used[q.front()]+1;q.push(n);}
n = q.front() + 1;
if(ok(n)){used[n] = used[q.front()]+1;q.push(n);
} n = q.front()*2;
if(ok(n)){used[n] = used[q.front()]+1;q.push(n);
} q.pop();
}
}
int main()
{
while(cin>>a>>b)
{
memset(used,0,sizeof(used));
q.push(a); used[a] = 1;
bfs();
cout<<used[b]-1<<endl;
while(!q.empty())
{
q.pop();
}
}
return 0;
}