Mother's Milk
Farmer John has three milking buckets of capacity A, B, and C liters. Each of the numbers A, B, and C is an integer from 1 through 20, inclusive. Initially, buckets A and B are empty while bucket C is full of milk.
Sometimes, FJ pours milk from one bucket to another until the second bucket is filled or the first bucket is empty. Once begun, a pour must be completed, of course. Being thrifty, no milk may be tossed out.
Write a program to help FJ determine what amounts of milk he can leave in bucket C when he begins with three buckets as above, pours milk among the buckets for a while, and then notes that bucket A is empty.
PROGRAM NAME: milk3INPUT FORMAT
A single line with the three integers A, B, and C.
SAMPLE INPUT (file milk3.in)
8 9 10
OUTPUT FORMAT
A single line with a sorted list of all the possible amounts of milk that can be in bucket C when bucket A is empty.
SAMPLE OUTPUT (file milk3.out)
1 2 8 9 10
SAMPLE INPUT (file milk3.in)
2 5 10
SAMPLE OUTPUT (file milk3.out)
5 6 7 8 9 10
肉流滿面終於ac了!!!每次偷懶遞迴太多層就stackoverflow。。
/*ID: des_jas1PROG: milk3LANG: C++*/#include <iostream>#include <fstream>#include <string>#include <string.h>#include <algorithm>#include <queue>//#define fin cin//#define fout coutusing namespace std;int capacity[3],bb[3];bool ans[25],k[21][21][21];int main() {ofstream fout ("milk3.out"); ifstream fin ("milk3.in");memset(ans,0,sizeof(ans));memset(bb,0,sizeof(bb));memset(k,0,sizeof(k));fin>>capacity[0]>>capacity[1]>>capacity[2];bb[2]=capacity[2]; queue<int> p;p.push(0);p.push(0);p.push(bb[2]);int i,j,a,b; while(!p.empty()) {for(i=0;i<3;i++){bb[i]=p.front(); p.pop();}if(!bb[0]) //若A是空的if(!ans[bb[2]]) //判斷c此時是否有被記錄過ans[bb[2]]=true;bool used[3];memset(used,0,sizeof(used));for(i=0;i<3;i++){if(bb[i]) //取某一個非空罐子{used[i]=true; //表示用它pourfor(j=0;j<3;j++){if(!used[j]) //尋找另外兩個罐子{if(bb[j]==capacity[j]) //被倒罐子滿就跳過break;a=bb[j]; //把當前倆罐子的容量記錄西來b=bb[i];while(bb[j]<capacity[j] && bb[i]) //一直到被倒罐子滿了 或者 另一個罐子空了{bb[j]++;bb[i]--;}if(!k[bb[0]][bb[1]][bb[2]]){k[bb[0]][bb[1]][bb[2]]=true; p.push(bb[0]); p.push(bb[1]); p.push(bb[2]);}bb[j]=a; //複原 bb[i]=b;}}used[i]=false;}} }for(i=0;ans[i]==false;i++);fout<<i;++i;for(;i<=20;i++)if(ans[i])fout<<" "<<i;fout<<endl;fout.close();fin.close(); return 0;}