时间限制: 2 Sec 内存限制: 128 MB
提交: 264 解决: 84
[提交][状态][讨论版][命题人:外部导入]
题目描述
【题目描述】
有三个容器,容量分别为 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了。
Input
【输入格式】
有多组测试数据。
输入a,b,c, k四个正整数( 100 ≥ a > b > c≥1 , 1≤k< 100 )
Output
【输出格式】
如果能得到k就输出两行。
第一行“yes”,第二行为最少的次数
否则输出“no”
Sample Input
10 7 3 5
Sample Output
yes
8
解题思路
采用set来记录入队信息,较好地平衡了 查找效率与内存消耗。
AC代码
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
#include<string>
#include<set>
using namespace std;
int k;
int c[3];
const int num_s=3; // 状态的数量
const int num_a=6; // 行动的数量
struct node{
int state[num_s];
int step;
string ops; //记录操作序列
};
// a->b
void pour(int s[], int a, int b){
if(s[a]+s[b]>c[b]){
s[a] = s[a]+s[b]-c[b];
s[b] = c[b];
}else{
s[b] = s[a]+s[b];
s[a] = 0;
}
}
// 状态转移函数;
node generate_NextState(node now, int action){
switch(action){
case 0: //a->b
pour(now.state, 0, 1);
break;
case 1: //b->a
pour(now.state, 1, 0);
break;
case 2: //a->c
pour(now.state, 0, 2);
break;
case 3: //c->a
pour(now.state, 2, 0);
break;
case 4: //b->c
pour(now.state, 1, 2);
break;
case 5: //c->b
pour(now.state, 2, 1);
break;
}
now.step ++;
now.ops.push_back(action +'0');
return now;
}
//状态向量的比较
int equalState(int state[], int endS[]){
for (int i=0; i<num_s; i++){
if(state[i] != endS[i]) return 0;
}
return 1;
}
// 是否完成目标。当前状态与终止状态的比较
int reachEnd(int state[]){
for (int i=0; i<3; i++){
if(state[i] == k) return 1;
}
return 0;
}
// 状态向量的输出
void printState(int a[]){
for(int i=0; i<num_s; i++){
printf("%d ", a[i]);
}
printf("\n");
}
// 结点合法性与重复性的检验
int inq(node now, set<int>& st){
int hash=0;
int product=1;
//构造对应的散列
for(int i=0; i<num_s; i++){
hash += now.state[i]* product;
product *= 110;
}
if(st.find(hash) == st.end()) {
st.insert(hash);
return 0;
}else return 1;
}
//广度优先搜索
int BFS(node b, node& ans){
set<int> st; //记录结点入队信息;
queue<node> q; //等待阅兵的队列
q.push(b);
inq(b, st);
do{
node now = q.front();
q.pop();
if( reachEnd(now.state) ) {
ans = now;
return now.step;
}
for(int i=0; i<num_a; i++){
node next = generate_NextState(now, i);
if( !inq(next, st) ){
// printState(next.state);
q.push(next);
}
}
}while(!q.empty());
return -1;
}
//主程序
int main(){
while(~scanf("%d%d%d%d", &c[0], &c[1], &c[2], &k)){
//初始化起点状态
node b={0};
b.state[0] = c[0];
//初始化目标状态(终止状态)
//检验
// printState(b.state);
// printState(e[0]);
//搜索
node ans;
if(~BFS(b, ans)) cout<<"yes"<<endl<<ans.step<<endl;
else cout<<"no"<<endl;
// cout<<ans.ops<<endl;
// string str = ans.ops;
// for(int i=0; i<str.length(); i++){
// b = generate_NextState(b, str[i]-'0');
// printState(b.state);
// }
}
return 0;
}