倒水问题 算法入门经典

#include 
#include 
#include 
#define maxn 1001
using namespace std;

struct node{
	int v1, v2, v3;
	int step;
	node operator = (node &t){
		v1 = t.v1;
		v2 = t.v2;
		v3 = t.v3;
		step = t.step;
	}
};
queue bufq;
int a, b, c, x, count, visit[maxn][maxn];
int bfs(){
	memset(visit, 0, sizeof(visit));
	while(!bufq.empty()) bufq.pop();
	node tmp;
	tmp.v1 = a; tmp.v2 = 0; tmp.v3 = 0; visit[0][0] = -1;
	tmp.step = 0; count = 0;
	bufq.push(tmp);
	while(!bufq.empty()){
		tmp = bufq.front();
		++count;
		bufq.pop();
		if(tmp.v1 == x || tmp.v2 == x || tmp.v3 == x)  return 1;
		node t = tmp;
		++tmp.step;
		if(tmp.v1 + tmp.v2 <= b){
			tmp.v2 += tmp.v1;
			tmp.v1 = 0;
		}
		else{
			tmp.v1 -= b - tmp.v2;
			tmp.v2 = b;
		}
		if(!visit[tmp.v2][tmp.v3]){
			visit[tmp.v2][tmp.v3] = count;
			bufq.push(tmp);
		}
		tmp = t;
		if(tmp.v1 + tmp.v3 <= c){
			tmp.v3 += tmp.v1;
			tmp.v1 = 0;
		}
		else{
			tmp.v1 -= c - tmp.v3;
			tmp.v3 = c;
		}
		if(!visit[tmp.v2][tmp.v3]){
			visit[tmp.v2][tmp.v3] = count;
			bufq.push(tmp);
		}
		tmp = t;
		if(tmp.v2 + tmp. v3 <= c){
			tmp.v3 += tmp.v2;
			tmp.v2 = 0;
		}
		else{
			tmp.v2 -= c - tmp.v3;
			tmp.v3 = c;
		}
		if(!visit[tmp.v2][tmp.v3]){
			visit[tmp.v2][tmp.v3] = count;
			bufq.push(tmp);
		}
		tmp = t;
		if(tmp.v2 + tmp.v1 <= a){
			tmp.v1 += tmp.v2;
			tmp.v2 = 0;
		}
		else{
			tmp.v2 -= a - tmp.v1;
			tmp.v1 = a;
		}
		if(!visit[tmp.v2][tmp.v3]){
			visit[tmp.v2][tmp.v3] = count;
			bufq.push(tmp);
		}
		tmp = t;
		if(tmp.v3 + tmp.v1 <= a){
			tmp.v1 += tmp.v3;
			tmp.v3 = 0;
		}
		else{
			tmp.v3 -= a - tmp.v1;
			tmp.v1 =a;
		}
		if(!visit[tmp.v2][tmp.v3]){
			visit[tmp.v2][tmp.v3] = count;
			bufq.push(tmp);
		}
		tmp = t;
		if(tmp.v3 + tmp.v2 <= b){
			tmp.v2 += tmp.v3;
			tmp.v3 = 0;
		}
		else{
			tmp.v3 -= b - tmp.v2;
			tmp.v2 = b;
		}
		if(!visit[tmp.v2][tmp.v3]){
			visit[tmp.v2][tmp.v3] = count;
			bufq.push(tmp);
		}
	}
	return 0;
}

int main(){
	cin>>a>>b>>c>>x;
	if(bfs()) 
	 cout<<"yes"<

你可能感兴趣的:(OJ)