Pots
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 25 Accepted Submission(s) : 11
Special Judge
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.
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int ans1[5000],ans2[5000];
string ss[7]={"\0","FILL(1)","FILL(2)","POUR(1,2)","POUR(2,1)","DROP(1)","DROP(2)" }; //最後輸出用的
int gcd(int n,int m){ //大家熟悉的輾轉相除法
if(m<=n){
return m==0?n:gcd(m,n%m);
}else{
return gcd(m,n);
}
}
int main()
{
int n,m,c;
while(~scanf("%d%d%d",&n,&m,&c)) //輸入
{
int r1=0,r2=0,sw=0,fw=0; //sw,fw分別代表兩個杯子裏剩下的水,r1,r2是記錄步數用的
if(c%gcd(n,m)!=0){printf("impossible\n");continue;}
while(sw!=c&&fw!=c)
{
if(!sw)
{
sw=m;
ans1[r1++]=2;
}
else if(fw==n)
{
fw=0;
ans1[r1++]=5;
}
else
{
ans1[r1++]=4;
fw+=sw; //先把水全部倒進一個瓶子裏
sw=0; //因爲水倒掉了,所以歸零
if(fw>=n){sw=fw-n;fw=n;} //把多出來的水倒回去
}
}
sw=0,fw=0;
while(sw!=c&&fw!=c)
{
if(!fw)
{
fw=n;
ans2[r2++]=1;
}
else if(sw==m)
{
sw=0;
ans2[r2++]=6;
}
else
{
ans2[r2++]=3; //和上面同理
sw+=fw;
fw=0;
if(sw>=m){fw=sw-m;sw=m;}
}
}
if(r1>r2) //輸出函數
{
cout<<r2<<endl;
for(int i=0;i<r2;i++)
cout<<ss[ans2[i]]<<endl;
}
else
{
cout<<r1<<endl;
for(int i=0;i<r1;i++)
cout<<ss[ans1[i]]<<endl;
}
}
return 0;
}