pots

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014443973/article/details/44984911

A - Pots
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Submit

Status
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)

该题为广搜算法,每次搜索有六种状态。
代码如下:

include

include

include

using namespace std;

const int MAX=105;
int a, b, c;
int visit[MAX][MAX];

struct node{
int a, b;
int steps;
};

node start;

struct node1{
int a, b;
int op;
}path[MAX][MAX];

void show(int count, int a, int b){
if(count == 0) return ;
show(count-1, path[a][b].a, path[a][b].b);
if(path[a][b].op==0) puts(“FILL(1)”);
else if(path[a][b].op==1) puts(“FILL(2)”);
else if(path[a][b].op==2) puts(“DROP(1)”);
else if(path[a][b].op==3) puts(“DROP(2)”);
else if(path[a][b].op==4) puts(“POUR(1,2)”);
else if(path[a][b].op==5) puts(“POUR(2,1)”);
}

bool bfs(node n){
memset(visit, 0, sizeof(visit));
queueq;
q.push(n);
visit[n.a][n.b] = 0;
node t, cur;
while(!q.empty()){
cur = q.front();
q.pop();
if(cur.a == c || cur.b == c){
printf(“%d\n”, cur.steps);
show(cur.steps, cur.a, cur.b);
return true;
}
for(int i = 0; i < 6; i++){
t = cur;
if(i == 0) {
t.a = a;
}
else if(i == 1){
t.b = b;
}
else if(i == 2){
t.a = 0;
}
else if(i == 3){
t.b =0;
}
else if(i == 4){
if(t.a+t.b < b){
t.b += t.a;
t.a = 0;
}
else {
t.a = t.a+t.b-b;
t.b = b;
}
}
else if(i == 5){
if(t.a+t.b < a){
t.a += t.b;
t.b = 0;
}
else {
t.b = t.a+t.b-a;
t.a = a;
}
}
if(!visit[t.a][t.b]){
path[t.a][t.b].a = cur.a;
path[t.a][t.b].b = cur.b;
path[t.a][t.b].op = i;
visit[t.a][t.b] = true;
t.steps++;
q.push(t);
}
}
}
return false;
}

int main(){
while(~scanf(“%d %d %d”, &a, &b, &c)){
start.a = start.b = start.steps = 0;
if(!bfs(start)) printf(“impossible\n”);
}
return 0;
}

展开阅读全文

没有更多推荐了,返回首页