POJ 3414 倒水(BFS+标记路径)

每日打卡(1/1)

传送门:点击打开链接

题目大意:

    瓶子1能装a升水,瓶子2能装b升水,问要装c升水最少要几步?

题解:

    明显的BFS,其中需要注意的地方就是记录路径。

    在结构体中设置一个node *pre,pre指向之前访问的操作,而结构体数组t也是BFS中一个比较新颖的操作。

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cmath>
#include<queue>
#include<stack>
#include<string>
using namespace std;
struct node{
	int x,y,tot,flag;
	node *pre;
}t[500];
stack<int> p;
int a,b,C,vis[110][110],counti = -1;

int bfs()
{
	memset(vis,0,sizeof(vis));
	node c;
	queue<node> q;
	c.x = 0;
	c.y = 0;
	c.tot = 0;
	c.pre = NULL;
	q.push(c);
	vis[c.x][c.y] = 1;
	
	while(!q.empty())
	{ 
		t[++counti] = q.front();
//		cout<<t[counti].x<<" "<<t[counti].y<<endl;
		q.pop();
		for(int i=0;i<6;i++)
		{
			switch(i)
			{
				case 0:
					c.x = a;
					c.y = t[counti].y;
					c.flag = 1;
					break;
				case 1:
					c.x = t[counti].x;
					c.y = b;
					c.flag = 2;
					break;
				case 2:
					c.x = 0;
					c.y = t[counti].y;
					c.flag = 3;
					break;
				case 3:
					c.x = t[counti].x;
					c.y = 0;
					c.flag = 4;
					break;
				case 4:
					if(t[counti].x>b-t[counti].y) {
						c.y = b;
						c.x = t[counti].x-(b-t[counti].y);
						c.flag = 5;
					}
					else {
						c.y = t[counti].x+t[counti].y;
						c.x = 0;
						c.flag = 5;
					}
					break;
				case 5:
					if(t[counti].y>a-t[counti].x) {
						c.x = a;
						c.y = t[counti].y-(a-t[counti].x);
						c.flag = 6;
					}
					else {
						c.x = t[counti].x+t[counti].y;
						c.y = 0;
						c.flag = 6;
					}
					break;
			}
//			cout<<c.x<<" "<<c.y<<endl;
			if(!vis[c.x][c.y]) {
				vis[c.x][c.y] = 1;
				c.tot = t[counti].tot+1;
				c.pre = &t[counti];
				if(c.x==C||c.y==C) {
				cout<<c.tot<<endl;
				while(c.pre)
				{
					p.push(c.flag);
					c = *c.pre;
				}
				while(!p.empty())
				{
					int flag = p.top();
					p.pop();
					switch(flag)
					{
						case 1:
							cout<<"FILL(1)"<<endl;
							break;
						case 2:
							cout<<"FILL(2)"<<endl;
							break;
						case 3:
							cout<<"DROP(1)"<<endl;
							break;
						case 4:
							cout<<"DROP(2)"<<endl;
							break;
						case 5:
							cout<<"POUR(1,2)"<<endl;
							break;
						case 6:
							cout<<"POUR(2,1)"<<endl;
							break;
					}
				}
				return 1;
			}
				q.push(c);
			}
		}
	}
	return 0;
}

int main()
{
	cin>>a>>b>>C;
	int ans = bfs();
	if(!ans) {
		cout<<"impossible"<<endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

总想玩世不恭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值