倒水问题 算法入门经典

#include <iostream>
#include <cstring>
#include <queue>
#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<node> 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"<<endl;
	else
	 cout<<"no\n"<<endl;
	 
	return 0;
} 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值