POJ3414倒水问题

题意:

有二个水壶,对水壶有三种操作:

1)FILL(i),将i水壶的水填满;

2)DROP(i),将水壶i中的水全部倒掉;

3)POUR(i,j)将水壶i中的水倒到水壶j中,若水壶 j 满了,则 i 剩下的就不倒了
问进行多少步操作,并且怎么操作,输出操作的步骤,两个水壶中的水可以达到C这个水量。如果不可能则输出impossible。初始时两个水壶是空的。

思路:BFS+路径输出

一共有6种操作,即一个6入口的BFS。
路径输出怎么办?
记录BFS每一层的节点,让子节点指向父节点,这样找到目标后既可以回溯了。

#include <cstdio>
#include <cstring>
#include <string> 
#include <queue>
#include <vector>
#include <algorithm>
#define first fi
#define second se
#define pii pair<int,int>
using namespace std;
typedef long long LL;
const int maxn = 100+5;

struct Node{
	int x,y;
	int step;
	int kind; // 操作类型
	Node *pre; 
	Node(int a = 0, int b = 0, int c = 0, int d = -1, Node* m = NULL):x(a),y(b),step(c),kind(d),pre(m){}
};

string actions[6] = {"FILL(1)", "FILL(2)", "DROP(1)", "DROP(2)","POUR(1,2)", "POUR(2,1)" };
int a,b,c, vis[maxn][maxn];
vector<int> opt;
int ans;

void bfs(){
	
	Node path[500];
	queue<Node> Q;
	Q.push(Node(0,0,0,-1,NULL));
	Node next;
	int cnt = -1; // 记录bfs过程中的节点 
	
	while(!Q.empty()){
		Node t = Q.front(); Q.pop();
		path[++cnt] = t;
		for(int i = 0; i < 6; ++i){
			switch(i){
				case 0: //fill 1
					next.x = a;
					next.y = t.y;
					next.kind = 0;
					break;
				case 1: // fill 2
					next.x = t.x;
					next.y = b;
					next.kind = 1;
					break;
				case 2: // drop 1
					next.x = 0;
					next.y = t.y;
					next.kind = 2;
					break;
				case 3: // drop 2
					next.x = t.x;
					next.y = 0;
					next.kind = 3;
					break;
				case 4: // pour 1 to 2
					if(t.x + t.y > b){
						next.x  = t.x - (b - t.y);
						next.y = b;
					}
					else{
						next.x = 0;
						next.y = t.x + t.y;
					}
					next.kind = 4;
					break;
				case 5: // pour 2 to 1
					if(t.x + t.y > a){
						next.y  = t.y - (a - t.x);
						next.x = a;
					}
					else{
						next.y = 0;
						next.x = t.x + t.y;
					}
					next.kind = 5;
			}
			if(vis[next.x][next.y]) continue;
			vis[next.x][next.y] = 1;
			
			next.step = t.step + 1;
			next.pre = &path[cnt]; //记录路径 
			
			if(next.x == c||next.y == c){
				ans = next.step;
				while(next.pre){
					opt.push_back(next.kind);
					next = *(next.pre);
				}
				return;
			}
			
			Q.push(next);
		}
	}
}

void print_path(){
	for(vector<int>::reverse_iterator it = opt.rbegin(); it != opt.rend(); ++it){
		int t = *it;
		printf("%s\n",actions[t].c_str());
		//cout<<actions[*it]<<endl;
	}
}

int main()
{
	freopen("in.txt","r",stdin);
	//printf("%s\n",actions[0].c_str());
	while(scanf("%d %d %d",&a,&b,&c) == 3){
		memset(vis, 0, sizeof(vis));
		vis[0][0] = 1;
		ans = -1;
		opt.clear();
		bfs();
		if(ans == -1) printf("impossible\n");
		else{
			printf("%d\n",ans);
			print_path();
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值