题目描述】
有三个容器,容量分别为 a,b,c(a> b > c ),一开始a装满油,现在问是否只靠abc三个容器量出k升油。如果能就输出“yes”,并且说明最少倒几次,否则输出“no”。例如:10升油在10升的容器中,另有两个7升和3升的空容器,要求用这三个容器倒油,使得最后在abc三个容器中有一个刚好存有5升油,问最少的倒油次数是多少?(每次倒油,A容器倒到B容器,或者A内的油倒完,或者B容器倒满。
10 7 3
(10 0 0)
(3 7 0):第一次
(3 4 3):第二次
(6 4 0):第三次
(6 1 3):第四次
(9 1 0):第五次
(9 0 1):第六次
(2 7 1):第七次
(2 5 3):第八次,出现5了。
自己测试都是对的,提交答案错误,目前还未解决
#include<cstdio>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
int cap[3];
map<int, bool> mp;
int endnum;
int src[6] = { 0,0,1,1,2,2 };
int tar[6] = { 1,2,0,2,0,1 };
struct node {
int a;
int b;
int c;
int step;
};
void pour(int target,int& s,int& t) {
if (s + t <= cap[target]) {
t = s + t;
s = 0;
}
else {
s = s - (cap[target] - t);
t = cap[target];
}
}
int to_num(int a, int b, int c) {
int ans = 0;
ans = a * 100 + b * 10 + c;
return ans;
}
void bfs() {
node top,mid;
int fff = 0;
queue<node> q;
mp.clear();
int tmp[3];
int source, target,flag;
top.a = cap[0];
top.b = 0;
top.c = 0;
flag = to_num(top.a, top.b, top.c);
mp[flag] = 1;
top.step = 0;
q.push(top);
while (!q.empty()) {
top = q.front();
q.pop();
for (int i = 0; i < 6; i++) {
source = src[i];
target = tar[i];
tmp[0] = top.a;
tmp[1] = top.b;
tmp[2] = top.c;
pour(target, tmp[source], tmp[target]);
flag = to_num(tmp[0], tmp[1], tmp[2]);
if (mp.find(flag) == mp.end()) {
mp[flag] = 1;
mid.a = tmp[0];
mid.b = tmp[1];
mid.c = tmp[2];
mid.step = top.step + 1;
q.push(mid);
if (mid.a == endnum || mid.b == endnum || mid.c == endnum) {
printf("yes\n");
/*printf("%d %d %d\n", top.a, top.b, top.c);
printf("%d %d %d\n", mid.a, mid.b, mid.c);*/
printf("%d\n", mid.step);
fff = 1;
return;
}
}
}
}
if (fff == 0) printf("no\n");
}
int main() {
while (scanf("%d", &cap[0]) != EOF) {
for (int i = 1; i < 3; i++) {
scanf("%d", &cap[i]);
}
scanf("%d", &endnum);
if (cap[0] == endnum) {
printf("yes\n");
printf("0\n");
}
else {
bfs();
}
//bfs();
}
}