给你两个杯子,问你怎么操作可以将这两个杯子其中一个杯子的容量达到目标状态,一共有三个操作
1,把杯子装满。
2,把杯子倒空。
3,一个杯子的水倒向另一杯子。
BFS。。
注意是一次输入一次输入一次输入!!!
我们把每种操作都进行标号,一共有6种,然后每进行一步操作,都记录下来,直到到达目标状态,然后回溯标号就可以。
#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<stack>
#include<set>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#include<sstream>
#define ll __int64
#define lll unsigned long long
#define MAX 1000009
#define MAXN 2009
#define eps 1e-8
#define INF 0x7fffffff
#define mod 1000000007
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
using namespace std;
struct node
{
int x,y,step,pre,flag;
};
int v1,v2,c;
node queue[MAX];
bool vis[109][109];
int path[MAX];
int index;
void bfs()
{
memset(vis,false,sizeof(vis));
int front = 0;
int rear = 0;
node u,v;
u.x = 0;
u.y = 0;
u.step = 0;
u.pre = -1;
vis[0][0] = true;
queue[rear++] = u;
while(front!=rear)
{
v = queue[front++];
if(v.x==c||v.y==c)
{
//cout<<v.x<<" "<<v.y<<" "<<v.step<<endl;
break;
}
node next;
for(int i = 0; i<6; i++)
{
if(i==0)
{
next.x = v1;
next.y = v.y;
next.flag = 0;
}
else if(i==1)
{
next.x = v.x;
next.y = v2;
next.flag = 1;
}
else if(i==2)
{
next.x = 0;
next.y = v.y;
next.flag = 2;
}
else if(i==3)
{
next.x = v.x;
next.y = 0;
next.flag = 3;
}
else if(i==4)
{
if(v.x + v.y>=v2)
{
next.x = v.x - (v2 - v.y);
next.y = v2;
}
else
{
next.x = 0;
next.y = v.x + v.y;
}
next.flag = 4;
}
else if(i==5)
{
if(v.x + v.y>=v1)
{
next.x = v1;
next.y = v.y - (v1 - v.x);
}
else
{
next.x = v.x + v.y;
next.y = 0;
}
next.flag = 5;
}
if(!vis[next.x][next.y])
{
next.step = v.step + 1;
next.pre = front - 1;
vis[next.x][next.y] = 1;
queue[rear++] = next;
}
}
}
if(front==rear)
{
puts("impossible");
return ;
}
index = 0;
for(int i = front - 1; i>=0;)
{
path[index++] = i;
i = queue[i].pre;
}
printf("%d\n",queue[front-1].step);
for(int i = index - 1; i>=0; i--)
{
int x = queue[path[i]].flag;
switch(x)
{
case 0:
printf("FILL(1)\n");
break;
case 1:
printf("FILL(2)\n");
break;
case 2:
printf("DROP(1)\n");
break;
case 3:
printf("DROP(2)\n");
break;
case 4:
printf("POUR(1,2)\n");
break;
case 5:
printf("POUR(2,1)\n");
break;
}
}
}
int main()
{
cin>>v1>>v2>>c;
bfs();
return 0;
}