Mother's Mil 母親的牛奶
阿新 • • 發佈:2018-12-12
1.4.4 Mother's Mil 母親的牛奶
Time Limit: 1 Sec Memory Limit: 64 MB
Description
農民約翰有三個容量分別是A,B,C升的桶,A,B,C分別是三個從1到20的整數,最初,A和B桶都是空的,而C桶是裝滿牛奶的。有時,約翰把牛奶從一個桶倒到另一個桶中,直到被灌桶裝滿或原桶空了。當然每一次灌注都是完全的。由於節約,牛奶不會有丟失。 寫一個程式去幫助約翰找出當A桶是空的時候,C桶中牛奶所剩量的所有可能性。
Input
單獨的一行包括三個整數A,B和C。
Output
只有一行,列出當A桶是空的時候,C桶牛奶所剩量的所有可能性。
Sample Input
8 9 10
Sample Output
1 2 8 9 10
思路:這個題應該用dfs,剛開始看到題,以為只需要分情況討論一下,然後寫了八個if,else然後wrong了好幾發,後來才知道要用dfs進行搜尋。
倒牛奶,無外乎就六種倒法,a->b , a->c , b->a , b->c , c->a , c->b ,只需要對這六種情況不斷搜尋就可以了,結束條件就是如果這種情況搜過了,就不需要再搜了,就return,然後有滿足條件的就記錄下來。
#include <stdio.h> #include <iostream> #include <algorithm> #include <set> using namespace std; set<int> s; int vis[22][22][22]={0}; int A,B,C; void dfs(int a,int b,int c) { if(vis[a][b][c]) return; vis[a][b][c]=1; if(a==0) s.insert(c); if(c>A-a) dfs(A,b,c-(A-a)); else dfs(a+c,b,0); if(c>B-b) dfs(a,B,c-(B-b)); else dfs(a,b+c,0); if(b>A-a) dfs(A,b-(A-a),c); else dfs(a+b,0,c); if(b>C-c) dfs(a,b-(C-c),C); else dfs(a,0,c+b); if(a>C-c) dfs(a-(C-c),b,C); else dfs(0,b,a+c); if(a>B-b) dfs(a-(B-b),B,c); else dfs(0,b+a,c); return ; } int main() { cin>>A>>B>>C; dfs(0,0,C); int i=0; set<int>::iterator it; for(it=s.begin();it!=s.end();it++) { if(!i) cout<<*it; else cout<<" "<<*it; i++; } cout<<endl; }