POJ 3414 Pots(bfs)

本文介绍了一个经典的两壶水问题,并提供了一种通过广度优先搜索算法来寻找从初始状态到目标状态最少操作步骤的方法。该算法使用队列进行状态的遍历,并记录每个状态的操作过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

两个壶,容量分别为A和B,问最少经过几次操作,其中一个壶的容量为C,输出流程

操作:

1.装满A或B

2.倒空A或B

3.A倒向B(要判断B已有的体积),B倒向A(要判断A已有的体积)

代码如下:

#include<cstdio>  
#include<cstring>
#include<queue>
#include<string>
using namespace std;
#define INF 1e7+9
typedef long long ll; 
const int N = 110; 
int a, b, c;
int vis[N][N];
int f[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
struct node
{
	int a, b, st;
	string ans;
};
node s, nex;

bool bfs()
{
	queue<node>q;
	while(!q.empty())q.pop();
	vis[0][0] = 1;
	s.a = 0, s.b = 0, s.st = 0;
	q.push(s);
	while(!q.empty())
	{
		s = q.front();
		q.pop();
		if(s.a == c || s.b == c) return true;
		int x, y;
		for(int i = 0; i < 6; i++)
		{
			if(i == 1) x = a, y = s.b;
			else if(i == 2) x = s.a, y = b;
			else if(i == 3)
			{
				if(s.a + s.b > a) x = a, y = s.a + s.b - a;
				else x = s.a + s.b, y = 0;
			} 
			else if(i == 4)
			{
				if(s.a + s.b > b) x = s.a + s.b - b, y = b;
				else x = 0, y = s.a + s.b;
			}
			else if(i == 5) x = 0, y = s.b;
			else x = s.a, y = 0;
			
			if(!vis[x][y])
			{
				vis[x][y] = 1;
				nex.a = x, nex.b = y, nex.st = s.st + 1;
				char c = i + '0';
				nex.ans = "";
				nex.ans += (s.ans + c);
				q.push(nex);
			}
		}
	}
	return false;
}

void output(char c)  
{  
    if (c == '1')  
        puts("FILL(1)");  
    else if (c == '2')  
        puts("FILL(2)");  
    else if (c == '3')  
        puts("POUR(2,1)");  
    else if (c == '4')  
        puts("POUR(1,2)");  
    else if (c == '5')  
        puts("DROP(1)");  
    else  
        puts("DROP(2)");  
}  

int main()
{
	while(~scanf("%d%d%d", &a, &b, &c))
	{
		memset(vis, 0, sizeof(vis));
		if(bfs())
		{
			printf("%d\n", s.st);
			for(int i = 0; i < s.st; i++)
			{
				output(s.ans[i]);
			}
		}
		else puts("impossible"); 
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值