hdu_1495_非常可乐(bfs模拟)

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1495

题意:不解释

题解:BFS模拟,不过要细心,把所有情况都列举出来,开一个数组记录状态,代码有点长,比较重复,尝试优化了一下,不过WA了难过

#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct dt{int s,m,n,t;};
int s,m,n;
bool v[101][101][101];
int bfs(){
	memset(v,0,sizeof(v));
	v[s][0][0]=1;
	dt tmp,o;tmp.s=s,tmp.m=0,tmp.n=0,tmp.t=0;
	queue<dt>Q;Q.push(tmp);
	while(!Q.empty()){
		o=Q.front();Q.pop();
		if((o.s==o.m&&!o.n)||(o.s==o.n&&!o.m)||(o.n==o.m&&!o.s))return o.t;
		if(o.s){
			if(o.m<m){
				if(o.s+o.m>=m){
					tmp.m=m,tmp.s=o.s+o.m-m,tmp.n=o.n,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}else{
					tmp.m=o.m+o.s,tmp.s=0,tmp.n=o.n,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}
			}
			if(o.n<n){
				if(o.s+o.n>=n){
					tmp.n=n,tmp.s=o.s+o.n-n,tmp.m=o.m,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}else{
					tmp.n=o.n+o.s,tmp.s=0,tmp.m=o.m,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
					}
			}
		}
		if(o.m){
			if(o.s<s){
				if(o.s+o.m>=s){
					tmp.s=s,tmp.m=o.m+o.s-s,tmp.n=o.n,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}else{
					tmp.s=o.s+o.m,tmp.m=0,tmp.n=o.n,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}
			}
			if(o.n<n){
				if(o.m+o.n>=n){
					tmp.n=n,tmp.m=o.m+o.n-n,tmp.s=o.s,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}else{
					tmp.n=o.n+o.m,tmp.m=0,tmp.s=o.s,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}
			}
		}
		if(o.n){
			if(o.m<m){
				if(o.n+o.m>=m){
					tmp.m=m,tmp.n=o.n+o.m-m,tmp.s=o.s,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}else{
					tmp.m=o.m+o.n,tmp.n=0,tmp.s=o.s,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}
			}
			if(o.s<s){
				if(o.n+o.s>=s){
					tmp.s=s,tmp.n=o.n+o.s-s,tmp.m=o.m,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}else{
					tmp.s=o.s+o.n,tmp.n=0,tmp.m=o.m,tmp.t=o.t+1;
					if(!v[tmp.s][tmp.m][tmp.n]){Q.push(tmp);v[tmp.s][tmp.m][tmp.n]=1;}
				}
			}
		}
	}
	return -1;
}
int main(){
	while(~scanf("%d%d%d",&s,&m,&n),s+n+m){
		if(s%2){puts("NO");continue;}
		int ans=bfs();
		if(ans==-1)puts("NO");
		else printf("%d\n",ans);
	}
	return 0;
}



你可能感兴趣的:(bfs)