题目描述
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的杯子,允许你用三种操作。
操作(i为1或2):
1.FILL(i), 在i杯里装满水
2.DROP(i), 把i杯里的水倒掉
3.POUR(i, j) 把i杯里的水倒入j杯,多余的部分留在i杯
通过上述操作使得到一个杯子使其里面有c的水。
要求步数最小,如果不能就输出impossible
模拟加bfs,就是写起来有点麻烦
用G++才能过,而且会在一些奇怪的地方语法错误,所以改成这样。
#include<iostream>
#include<cstring>
#include<string>
#include<queue>
#include<map>
using namespace std;
typedef pair<int, int> PII;
int a, b, c;
map<PII, string> mp;
map<PII, int> st;
PII t;
int bfs()
{
queue<PII> q;
t = {0, 0};
q.push(t);
st[t] = 0;
mp[t] = "";
while(q.size())
{
t = q.front();
q.pop();
int x = t.first, y = t.second;
if(x == c || y == c) return st[t];
PII m;
m = {a, y};
if(!st[m])
{
q.push(m);
st[m] = st[t] + 1;
mp[m] = mp[t] + '1';
}
m = {x, b};
if(!st[m])
{
q.push(m);
st[m] = st[t] + 1;
mp[m] = mp[t] + '2';
}
m = {0, y};
if(!st[m])
{
q.push(m);
st[m] = st[t] + 1;
mp[m] = mp[t] + '3';
}
m = {x, 0};
if(!st[m])
{
q.push(m);
st[m] = st[t] + 1;
mp[m] = mp[t] + '4';
}
if(x + y >= b) m = {x + y - b, b};
else m = {0, x + y};
if(!st[m])
{
q.push(m);
st[m] = st[t] + 1;
mp[m] = mp[t] + '5';
}
if(x + y >= a) m = {a, x + y - a};
else m = {x + y, 0};
if(!st[m])
{
q.push(m);
st[m] = st[t] + 1;
mp[m] = mp[t] + '6';
}
}
return -1;
}
int main()
{
cin >> a >> b >> c;
int ans = bfs();
if(ans != -1)
{
cout << ans << endl;
string s = mp[t];
for(int i = 0; i < s.size(); i++)
{
int f = s[i] - '0';
if(f <= 2)
cout << "FILL(" << f << ")" << endl;
else if(f <= 4)
cout << "DROP(" << f - 2 << ")" << endl;
else
cout << "POUR(" << f - 4 << "," << 7 - f << ")" << endl;
}
}
else cout << "impossible" << endl;
return 0;
}