POJ 3278(bfs)
虽然是水题,但要注意数组的越界和vis的使用,不然就RE、TLE
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=100005;
const double eps=1e-8;
const double PI = acos(-1.0);
struct node
{
int d,time;
node(int a,int b):d(a),time(b) {}
node() {}
};
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int n,k;
while(cin>>n>>k)
{
bool vis[100005]= {0};
queue<node> q;
node s;
s.d=n;
s.time=0;
q.push(s);
vis[n]=1;
while(!q.empty())
{
node t=q.front();
if(t.d==k)
{
cout<<t.time<<endl;
break;
}
q.pop();
int flag=0;
for(int i=0; i<3; i++)
{
if(i==0&&t.d+1<maxn&&!vis[t.d+1])
{
node a(t.d+1,t.time+1);
q.push(a);
if(a.d==k)
{
cout<<a.time<<endl;
flag=1;
break;
}
vis[t.d+1]=1;
}
else if(i==1&&t.d>0&&!vis[t.d-1])
{
node a(t.d-1,t.time+1);
q.push(a);
if(a.d==k)
{
cout<<a.time<<endl;
flag=1;
break;
}
vis[t.d-1]=1;
}
else if(i==2&&t.d*2<maxn&&!vis[t.d*2])
{
node a(t.d*2,t.time+1);
q.push(a);
if(a.d==k)
{
cout<<a.time<<endl;
flag=1;
break;
}
vis[t.d*2]=1;
}
}
if(flag)
break;
}
}
return 0;
}