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: milk3
INPUT 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_jas1
PROG: milk3
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <algorithm>
#include <queue>
//#define fin cin
//#define fout cout
using 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; //表示用它pour
for(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;
}