POJ 3414 Pots(水壶)

来源:互联网 发布:用户注册页面js代码 编辑:程序博客网 时间:2024/04/27 22:58

题目链接:POJ 3414

题意:

给两个容量分别为A,B的水壶,标号为1和2,初始水量都是0。每次操作有如下三种选择:

①FILL(i),将i水壶灌满(i=1或2)

②POUR(i),将i水壶中水倒完(i=1或2)

③DROP(i,j)。从i水壶倒水进j水壶,将j水壶倒满或i水壶中水倒完。

问能否经过若干次操作,使得其中一个水壶中的水量是C?

如果能,输出操作次数,以及操作历程;否则输出“impossible”。

思路:

用队列模拟操作过程。每次都有6种选择,但是需要判断下能否进行。例如FILL(i)时,得满足i不是已经满了。这里需要考虑队列中每个元素的类型。可以设计一个结构体类型,每个变量存储两个水壶的水量,操作次数,以及到达这步时的操作历程。

#include <iostream>#include <cstring>#include <string>#include <queue>#include <algorithm>#include <cstdio>using namespace std;const int maxn = 1000;//maxn是最多模拟次数,按照A,B最大为100算的话,实际上最多应为100*100,但是1000已经可以AC了~int A, B, C;int vis[105][105];//vis[i][j]=1表示第一个水壶水量为i第二个水壶水量为j的情况已经模拟过了struct Node {int a, b, step;//a,b分别是1,2水壶的容量,step是操作次数char s[maxn][15];}head, newnode, temp;void BFS(){queue<Node> q;memset(vis, 0, sizeof(vis));head.a = head.b = head.step = 0;q.push(head);while (!q.empty()){temp = q.front();q.pop();if (temp.a == C || temp.b == C){cout << temp.step << endl;for (int j = 1;j <= temp.step;j++)cout << temp.s[j] << endl;return;}newnode.step = temp.step + 1;for (int i = 1;i <= temp.step;i++)strcpy(newnode.s[i], temp.s[i]);//将之前的操作历程复制过来for (int i = 0;i < 6;i++)//每次新的操作有6种选择{if (i == 0){//FILL(1)if (temp.a != A){//排除1水壶已经满的情况newnode.a = A;newnode.b = temp.b;strcpy(newnode.s[newnode.step], "FILL(1)");//记录本次操作}}else if (i == 1)//DROP(1){if (temp.a != 0){//排除1水壶已经空的情况newnode.a = 0;newnode.b = temp.b;strcpy(newnode.s[newnode.step], "DROP(1)");}}else if (i == 2){//POUR(1,2)if (temp.b != B){//排除2水壶已经满的情况if (temp.a + temp.b > B){//1水壶倒不完newnode.a = temp.a + temp.b - B;newnode.b = B;}else{newnode.a = 0;newnode.b = temp.a + temp.b;}strcpy(newnode.s[newnode.step], "POUR(1,2)");}}else if (i == 3){//i=3,4,5时和以上类似if (temp.b != B){newnode.a = temp.a;newnode.b = B;strcpy(newnode.s[newnode.step], "FILL(2)");}}else if (i == 4){if (temp.b != 0){newnode.a = temp.a;newnode.b = 0;strcpy(newnode.s[newnode.step], "DROP(2)");}}else if (i == 5){if (temp.a != A){if (temp.a + temp.b > A){newnode.a = A;newnode.b = temp.a + temp.b - A;}else{newnode.a = temp.a + temp.b;newnode.b = 0;}strcpy(newnode.s[newnode.step], "POUR(2,1)");}}if (!vis[newnode.a][newnode.b]){//如果新产生的情形以前没有出现过,那么将它压入队列q.push(newnode);vis[newnode.a][newnode.b] = 1;}}}//将所有可能的情形都模拟完了,仍然不能使得任一水壶水量达到C,那么就是impossible了cout << "impossible" << endl;}int main(){#ifdef LOCALfreopen("in.txt", "r", stdin);freopen("out.txt", "w", stdout);#endifwhile (cin>>A>>B>>C){BFS();}return 0;}


0 0
原创粉丝点击