USACO1.4 Mother's Milk(milk3)

       三个桶容量为a,b,c,当前牛奶量分别是x,y,z,使用dfs+递归搜索全部解,中止条件是当前的组合(x,y,z)已经搜索过,用数组found[][][]来保存和检测当前组合是否搜索过。每一个合适的z值,保存进set中自动排序,搜索完毕后,依次输出即可。

 

/*
ID:jzzlee1
PROG:milk3
LANG:C++
*/
#include<iostream>
#include<fstream>
#include<cstring>
#include<set>
using namespace std;
int a,b,c;      //各桶容量
bool found[21][21][21];     //保存是否搜索过,作为递归的中止条件
set<int> set1;
ifstream fin("milk3.in");
ofstream fout("milk3.out");
void dfs(int x,int y,int z)
{
     if (found[x][y][z]) return;
     found[x][y][z]=true;
     if (x==0)
		set1.insert(z);//将满足条件的z值放进set中自动排序
     if (x<=b-y) dfs(0,y+x,z);             //x->y     
     else dfs(x-(b-y),b,z);
     if (x<=c-z) dfs(0,y,z+x);             //x->z
     else dfs(x-(c-z),y,c);
     if (y<=a-x) dfs(x+y,0,z);             //y->x     
     else dfs(a,y-(a-x),z);
     if (y<=c-z) dfs(x,0,z+y);             //y->z
     else dfs(x,y-(c-z),c);
     if (z<=a-x) dfs(x+z,y,0);             //z->x     
     else dfs(a,y,z-(a-x));
     if (z<=b-y) dfs(x,y+z,0);             //z->y
     else dfs(x,b,z-(b-y));
     return;
}
 
int main()
{
    memset (found,0,sizeof(found));
    fin >>a >>b >>c;
	//cin>>a>>b>>c;
    dfs(0,0,c);
	set<int>::iterator iter;int i=0;
    for (iter=set1.begin();iter!=set1.end();++iter,++i)//输出
    {
        if (i!=0)
			fout <<' ';
			//cout<<" ";
        fout <<*iter;
		//cout<<*iter;
    }
	//cout<<endl;
    fout <<endl;
    return 0;
}

你可能感兴趣的:(USACO)