POJ 3414 Pots(bfs)

博客围绕给定两个水杯容量,探讨能否通过A倒B、A倒干水、A倒满水等操作得到C毫升的水,涉及POJ相关问题及bfs算法。

题意:给你2个水杯的容量,问能否通过以下操作得到C毫升的水

  1. A倒B(B倒A)
  2. A倒干水(B倒干水)
  3. A倒满水(B倒满水)
     
#include<cstdio>  
#include<cstring>  
#include<cstdlib>  
#include<cmath>  
#include<iostream>  
#include<algorithm>  
#include<vector>  
#include<map>  
#include<set>  
#include<queue>  
#include<string>   
using namespace std;  
#define N int(2000)  
#define inf int(0x3f3f3f3f)  
#define mod int(1e9+7)  
typedef long long LL;
struct point
{
	int A,B,step;
	string path;
	point(int _a,int _b,int _stp,string _s){
		A=_a;
		B=_b;
		step=_stp;
		path=_s;
	}
	point(){}
};
set< pair<int,int> > st;

void bfs(const int a,const int b,const int c)
{
	st.clear();
	st.insert(make_pair(0,0));
	queue<point>q;
	q.push(point(0,0,0,""));
	point top;
	while(!q.empty())
	{
		top=q.front();q.pop();
		if(top.A==c||top.B==c)
		{
			printf("%d\n",top.step);
			printf("%s",top.path.c_str());
			return ;
		}
		for(int i=0;i<6;i++)
		{
			int x=top.A;
			int y=top.B;
			int stp=top.step;
			string tpath=top.path;
			if(i==0)//FILL A
			{
				tpath+="FILL(1)";
				x=a;
			}
			else if(i==1)//FILL B
			{
				tpath+="FILL(2)";
				y=b;
			}
			else if(i==2)//POUR AtoB
			{
				tpath+="POUR(2,1)";
				int por=min((a-x),y);
				x+=por;
				y-=por;
			}
			else if(i==3)//POUR BtoA
			{
				tpath+="POUR(1,2)";
				int por=min((b-y),x);
				x-=por;
				y+=por;
			}
			else if(i==4)//DROP A
			{
				tpath+="DROP(1)";
				x=0;
			}
			else if(i==5)//DROP B
			{
				tpath+="DROP(2)";
				y=0;
			}
			if(!st.count(make_pair(x,y)))
			{
				tpath+='\n';
				st.insert(make_pair(x,y));
				q.push(point(x,y,stp+1,tpath));
			}
		}
	}
	puts("impossible");
	return ;
}
int main()  
{  
#ifdef CDZSC  
    freopen("i.txt", "r", stdin);  
    //freopen("o.txt","w",stdout);  
    int _time_jc = clock();  
#endif  
	int a,b,c;
	while(~scanf("%d%d%d",&a,&b,&c))
	{
		bfs(a,b,c);
	}
    return 0;  
}  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值