BZOJ 1646:[Usaco2007 Open]Catch That Cow 抓住那只牛

bfs一遍

不解释

#include<set>
#include<map>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<cstdio>
#include<vector>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define g getchar()
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
inline ll read(){
	ll x=0,f=1;char ch=g;
	for(;ch<'0'||ch>'9';ch=g)if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=g)x=x*10+ch-'0';
	return x*f;
}
inline void out(ll x){
	int a[25],wei=0;
	if(x<0)putchar('-'),x=-x;
	for(;x;x/=10)a[++wei]=x%10;
	if(wei==0){puts("0");return;}
	for(int j=wei;j>=1;--j)putchar('0'+a[j]);
	putchar('\n');
}
int n,m,pd[1000000],dis[1000000],dui[1000000],ans[1000000];
int bfs(int n,int m){
	memset(pd,0,sizeof(pd));
	memset(ans,inf,sizeof(ans));
	int tou=1,wei=1;
	dui[1]=n;ans[n]=0;
	for(;tou<=wei;pd[dui[tou++]]=0){
		int u=dui[tou];
		if(u&&ans[u-1]>ans[u]+1){
			ans[u-1]=ans[u]+1;
			if(!pd[u-1]){
				dui[++wei]=u-1;
				pd[u-1]=1;
			}
		}
		if(u<m&&ans[u*2]>ans[u]+1){
			ans[u*2]=ans[u]+1;
			if(!pd[u*2]){
				dui[++wei]=u*2;
				pd[u*2]=1;
			}
		}
		if(u<m*2&&ans[u+1]>ans[u]+1){
			ans[u+1]=ans[u]+1;
			if(!pd[u+1]){
				dui[++wei]=u+1;
				pd[u+1]=1;
			}
		}
	}
}
int main(){
//	freopen("","r",stdin);
//	freopen("","w",stdout);
	n=read();m=read();
	bfs(n,m);
	out(ans[m]);
	return 0;
}


相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页