Pots
Description You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
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) Source
Northeastern Europe 2002, Western Subregion
|
思路如下:
当这两个杯子中较大的一个是较小的倍数且第三个杯子不是较小杯子的倍数时,则不可能产生和第三个杯子相同体积的水;如果能够产生相同体积的水,1,,当第二个杯子为空时往第二个杯子里面倒水,当一个杯子满是则把水全部倒掉,否则把第二个杯子的水倒入第一个杯子里面,直到有一个杯子里面的水的体积和第三个杯子的一致。2,当第一个杯子为空时,往第一个杯子里倒水,当第二个杯子满时则倒掉,否则把第一个杯子里面的水倒入第二个杯子里面,直到有一个杯子里面水的体积等于第三个杯子。去移动次数最少的那次,输出即可。
附关于sscanf的一些用法:
http://blog.youkuaiyun.com/i1020/article/details/53557116
#include <stdio.h>
char str1[5000][20],str2[5000][20];
int main(){
int a,b,c,cnt1,cnt2;
while(~scanf("%d%d%d",&a,&b,&c)){
int t1 = a > b ? a : b;
int t2 = a + b - t1;
cnt1 = 0;
if(t1 % t2 == 0 && c % t2 != 0)//来判断是否能够产生C升
printf("impossible\n");
else{
int i = 0, j = 0;//i表示第二个空杯子,j表示第一个空杯子
while(i != c && j != c){//先往第二个空杯子里面倒
if(!i){//第二个杯子为空,直接倒满
i = b;
sscanf("FILL(2)\n","%s",str1[cnt1++]);
}
else if(j == a){//第一个杯子满则倒掉
j = 0;
sscanf("DROP(1)\n","%s",str1[cnt1++]);
}
else{//把第二个杯子的水倒入第一个杯子里
int tmp = i;
i -= (a - j);
sscanf("POUR(2,1)\n","%s",str1[cnt1++]);
if(i < 0)
i = 0;
j += tmp;
if(j > a)
j = a;
}
}
i = 0; j = 0; cnt2 = 0;
while(i != c && j != c){//原理同上个while循环
if(!j){
j = a;
sscanf("FILL(1)\n","%s",str2[cnt2++]);
}
else if(i == b){
i = 0;
sscanf("DROP(2)\n","%s",str2[cnt2++]);
}
else{
int tmp = j;
j -= (b - i);
if(j < 0)
j = 0;
i += tmp;
if(i > b)
i = b;
sscanf("POUR(1,2)\n","%s",str2[cnt2++]);
}
}
printf("%d\n",cnt1 < cnt2 ? cnt1 : cnt2);//输出最少次数
if(cnt1 > cnt2){
for(i = 0; i < cnt2; i ++)
printf("%s\n",str2[i]);
}
else{
for(i = 0; i < cnt1; i ++)
printf("%s\n",str1[i]);
}
}
}
return 0;
}