pku acm 3278源码

#include <iostream>
#include <cstring>
using namespace std;

int n,k;
const int N=100001;
int Q[N];
int visited[N];
int ans[N];

int bfs(int x)
{
	if (x>=k)
		return (x-k);

	visited[x]=1;
	Q[0]=x;
	int first=-1,last=0;

	while (first!=last)
	{
		int v=Q[++first];

		if (v==k)
		   return ans[v];
        
		int tmpx=v+1;
		if (tmpx>=0 && tmpx<N &&visited[tmpx]==0)
		{
			Q[++last]=tmpx;                     
			visited[tmpx] = 1; 
			ans[tmpx]=ans[v]+1;
		}  

		tmpx=v-1;
		if (tmpx>=0 && tmpx<N &&visited[tmpx]==0)
		{ 
			Q[++last]=tmpx;                     
			visited[tmpx] = 1;
			ans[tmpx]=ans[v]+1;
		}

		

		tmpx=v*2;
		if (tmpx>=0 && tmpx<N &&visited[tmpx]==0)
		{
			Q[++last]=tmpx;                     
			visited[tmpx] = 1; 
			ans[tmpx]=ans[v]+1;
		}   
	}
}

int main()
{
	while(cin>>n>>k)
	{
		memset(visited,0,sizeof(visited));
		memset(Q,0,sizeof(Q));
		memset(ans,0,sizeof(ans));
		cout<<bfs(n)<<endl;
	} 
	return 0;
}

你可能感兴趣的:(ACM,bfs,pku,3278)