1. 程式人生 > >隨手練——USACO 1.44 母親的牛奶

隨手練——USACO 1.44 母親的牛奶

兩種 urn through idt wid == space using data

P1215 [USACO1.4]母親的牛奶 Mother‘s Milk


洛谷 P1215:https://www.luogu.org/problemnew/show/P1215

技術分享圖片

解題思想:DFS

大一校內編程比賽的題目了,當時毛都沒看懂,現在再拿出來,不能說小意思吧,中等意思吧,

一個杯子往另一個杯子裏倒,分兩種情況。

假設A杯,B杯(大小關系是不影響的,反過來一樣):

技術分享圖片

需要註意的就是,添加一個flag數組,已經做過的狀態,下次不再做了,否則這個遞歸就是個環了。

#include <iostream>
#include <set>
using namespace std;

set<int>s; bool flag[21][21][21]; int A, B, C; int min(int a,int b) { return a < b ? a : b; } void DFS(int a,int b,int c) { if (flag[a][b][c])return; else flag[a][b][c] = true; if (a > A || b > B || c > C) { return; } if (a == 0) { s.insert(c); }
if (a > 0) { //a->b DFS(a - min(B - b, a), b + min(B - b, a), c); //a->c DFS(a - min(C - c, a), b, c + min(C - c, a)); } if (b > 0) { //b->a DFS(a + min(b, A - a), b - min(b, A - a), c); //b->c (a, b - min(b, C - c), c + min(C - c, b)); }
if (c > 0) { //c->a DFS(a + min(A - a, c), b, c - min(A - a, c)); //c->b DFS(a, b + min(B - b, c), c - min(c, B - b)); } } int main() { int i = 0; cin >> A >> B >> C; DFS(0, 0, C); set<int>::iterator it = s.begin(); while (it != s.end()) { if ((i++) == s.size() - 1)break; cout << *it << " "; it++; } cout << *it << endl; return 0; }

隨手練——USACO 1.44 母親的牛奶