POJ 3414
Description
You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
- FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
- DROP(i) empty the pot i to the drain;
- POUR(i,j) pour from pot i to pot j; after this operation either the pot j is full (and there may be some water left in the pot i), or the pot i is empty (and all its contents have been moved to the pot j).
Write a program to find the shortest possible sequence of these operations that will yield exactly C liters of water in one of the pots.
Input
On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 and C≤max(A,B).
Output
The first line of the output must contain the length of the sequence of operations K. The following K lines must each describe one operation. If there are several sequences of minimal length, output any one of them. If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.
Sample Input
3 5 4
Sample Output
6 FILL(2) POUR(2,1) DROP(1) POUR(2,1) FILL(2) POUR(2,1)
题目大意:输入三个数A、B、C,分别为A、B容器的容量大小,和想要用A、B容器倒出的数值C。(A、B容器没有刻度)规定有3种操作 ,将某个容器用水倒满,将某个容器内的水清空,把某个容器内的
水倒入另一个容器。具体的A、B容器,就有6种操作,(水→A,水→B,A→水,B→水,A→B,B→A)。如果仅靠上诉操作能够倒出C时,输出最少的操作步数,以及每一步的操作;不能时输出 impossible
思路:这题我自己wa了好久也没做对,最后参考了大佬的代码。链接如下:https://blog.csdn.net/w144215160044/article/details/50599736
全部代码我这里就不粘了,主要说一下大佬的做法。使用优先队列来存放每一步操作后的结果,用数组标记状态,一个结构体表示当前容器内的水,另一个结构体记录容器的这个结果的上一步进行了那种
操作和上一步时容器内水的多少。使用这个方法回溯,其他的地方直接搜就ok。主要代码如下:
struct node1//保存信息用以回溯 { int prea, preb, op; }pots[N][N]; struct node//操作到某一步时,容器内水的多少以及操作步数 { int a, b, step; bool friend operator < (const node &a, const node &b) { return a.step > b.step; } }p, q; int a, b, c, flag, path[N*20000], vis[N][N];//路径信息以及标记信息 if (!vis[p.a][p.b]) { vis[p.a][p.b] = 1; pots[p.a][p.b].prea = q.a;//记录信息,这里仔细想一下 pots[p.a][p.b].preb = q.b; pots[p.a][p.b].op = i; p.step = q.step + 1; que.push (p); } for (int i=step; i>=1; i--)//利用node1进行回溯,找到每一步的操作 { path[i] = pots[x][y].op; int xx = x; x = pots[x][y].prea; y = pots[x][y].preb; }

浙公网安备 33010602011771号