USACO1.4 Mother's Milk(milk3)

       三個桶容量爲a,b,c,當前牛奶量分別是x,y,z,使用dfs+遞歸搜索所有解,停止條件是當前的組合(x,y,z)已經搜索過,用數組found[][][]來保存和檢測當前組合是否搜索過。每個合適的z值,保存進set中自動排序,搜索完畢後,依次輸出便可。ios

 

/*
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;
}
相關文章
相關標籤/搜索