POJ 3414 (BFS)

15 篇文章 0 订阅
14 篇文章 0 订阅

点此进入题目链接:POJ 3414

思路 :这题给 给这个 题目一样  HDU - 1495 非常可乐 一样 只不过需要记录路径

AC:代码

#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
#include<math.h>
#include<algorithm>
#include<vector>
#include<string.h>
using namespace std;
const int maxn = 101;
bool inq[maxn][maxn] = {0};
int w[2], c;
struct node{
	int water[2];
	int step;
	string s;
	int pre;
	int index;
	node(){
		s = "";
		step = 0;
		pre = -1;
		index = 0;
	}
}op[1002];

node BFS(){
	queue<node> q;
	node start;
	op[0].water[0] = 0;
	op[0].water[1] = 0;
	op[0].step = 0;
	op[0].pre = -1;
	op[0].index = 0;
	q.push(op[0]);
	inq[0][0] = 1;
	
	node front, next;
	int p = 1;
	string s;
	while(!q.empty()){
		front = q.front();
		q.pop();
		if(front.water[0] == c || front.water[1] == c){
			return front;
		}
		for(int i = 0; i < 2;i ++){
			for(int j = 0; j < 2; j++){
				next = front;
				
				if(i == j && next.water[i] != w[i]){ //倒满 
					next.water[i] = w[i];
					char x = i + '0' + 1;
					s = "";
					s += "FILL(";
					s += x;
					s += ")";
					next.s = s;
				}else if(front.water[i] > 0 && front.water[j] < w[j]){	// i 向 j 倒水 
					char x = i + '0' + 1;
					char y = j + '0' + 1;
					s = "";
					s += "POUR(";
					s += x;
					s += ",";
					s += y; 
					s += ")";
					next.s = s;
					int temp = w[j] - front.water[j];
					if(front.water[i] >= temp){
						next.water[i] -= temp;
						next.water[j] = w[j];
					} else{
						next.water[i] = 0;
						next.water[j] += front.water[i];
					}	
				}
				if( !inq[next.water[0]][next.water[1]] ){
					next.step += 1;
					next.index = p;
					next.pre = front.index;
					op[p++] = next;
					inq[next.water[0]][next.water[1]] = 1;
					q.push(next);
				} 
			}
		} 
		for(int i = 0; i < 2; i++){	// 倒出 
			next = front;
			next.water[i] = 0;
			char x = i + '0' + 1;
			s = "";
			s += "DROP(";
			s += x;
			s += ")";
			next.s =  s;
			if( !inq[next.water[0]][next.water[1]] ){
				next.step += 1;
				next.pre = front.index;
				next.index = p;
				op[p++] = next; 
				inq[next.water[0]][next.water[1]] = 1;
				q.push(next);
			}
		}
	}
	node end;
	end.index = -1;
	return end;
}
void Printf(node ans){
	if(ans.pre == -1){
		return ;	
	}
	else{
		Printf( op[ans.pre] );
		cout << ans.s << endl;
	}
}
int main (){
	cin >> w[0] >> w[1] >> c;
	node ans = BFS();
	if(ans.index == -1){
		cout << "impossible" << endl;
	}else{
		cout << ans.step  << endl;
		Printf(ans);
	}
    return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值