Mother's Milk - USACO 1.4.4


mother'smilk - codetrick
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
http://mangogao.com/read/89.html
农民约翰有三个容量分别是A,B,C升的桶,A,B,C分别是三个从1到20的整数, 最初,A和B桶都是空的,而C桶是装满牛奶的。有时,农民把牛奶从一个桶倒到 另一个桶中,直到被灌桶装满或原桶空了。当然每一次灌注都是完全的。由于节约, 牛奶不会有丢失。
写一个程序去帮助农民找出当A桶是空的时候,C桶中牛奶所剩量的所有可能性。

http://jusaco.blogspot.com/2013/07/mothers-milk-training.html
X. DFS
http://www.icycandy.com/blog/usaco-1-4-4-mothers-milk
https://tausiq.wordpress.com/2010/11/26/usaco-mothers-milk/
设res[j]为C桶中牛奶量为j的可能性
status[i][j]为A桶有i牛奶,C桶有j牛奶的可能性,初态为i==0;j==C;
当i==0时置res[j]=true;
总共有六种倒法A->B,A->C,B->A,B->C,C->A,C->B
对每种status,分别搜索这六种倒法.
用DFS解。用searched[x][y]数组记录搜索过的状态,不使用三维数组是因为前2维决定了第三维。用amount[z]的布尔值记录当x=0时z的值。 

private static boolean[][] searched = new boolean[21][21];
private static boolean[] amount = new boolean[21];
private static int a,b,c;
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new FileReader("milk3.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("milk3.out")),true);
//read data
StringTokenizer st = new StringTokenizer(in.readLine());
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
dfs(0,0,c);
for (int i = 0;i < c;i++)
if (amount[i])
out.print(i + " ");
out.println(c);
System.exit(0);
}
private static void dfs(int x, int y, int z){
if(searched[x][y]) return;
searched[x][y] = true;
if(x == 0) amount[z] = true;
if (x>0 && y<b)
dfs(max(0,x+y-b),min(b,x+y),z);
if (x>0 && z<c)
dfs(max(0,x+z-c),y,min(c,x+z));
if (y>0 && x<a)
dfs(min(a,y+x),max(0,y+x-a),z);
if (y>0 && z<c)
dfs(x,max(0,y+z-c), min(c,y+z));
if (z>0 && x<a)
dfs(min(a,z+x),y,max(0,z+x-a));
if (z>0 && y<b)
dfs(x,min(b,z+y),max(0,z+y-b));
}

bool res[21]={0};
bool status[21][21]={0}; //status[i][j]表示A有i牛奶,C有j牛奶的可能
int a,b,c,p,q;
 
int main()
{
    ifstream fin("milk3.in");
    ofstream fout("milk3.out");
 
    int s=0,i,j=0;
    fin>>a>>b>>c;
    search(0,c);
 
    for (i=0;i<=20;i++) if (res[i]) s++;
    for (i=0;i<=20;i++)
    {
        if (res[i])
        {
            fout<<i;
            j++;
            if (j==s) fout<<endl;
            else fout<<’ ‘;
        }
    }
 
    fin.close();
 
    fout.close();
 
    return 0;
}
 
void search(int ma,int mc)
{
    if (status[ma][mc]) return;
 
    int mb=c-ma-mc;
    status[ma][mc]=true;
    if (ma==0) res[mc]=true;
 
    search(ma-min(ma,b-mb),mc); //a->b
    search(ma-min(ma,c-mc),mc+min(ma,c-mc)); //a->c
    search(ma+min(mb,a-ma),mc); //b->a
    search(ma,mc+min(mb,c-mc)); //b->c
    search(ma+min(a-ma,mc),mc-min(a-ma,mc)); //c->a ma + min(mc,a-ma),
    search(ma,mc-min(b-mb,mc)); //c->b
}
X. BFS
http://qingtangpaomian.iteye.com/blog/1635111
用BFS逐层产生可能有的A,B,C三个桶的牛奶数量。如果已经产生过了则不用进入bfs的队列了,所以我们用一个hash表记录所有已经产生的状态。
          如果bfs的队列当中没有元素了,则程序结束,输出所有已经产生的结果。
  1.     public static void main(String[] args) {  
  2.         try {  
  3.             Scanner in = new Scanner(new BufferedReader(new FileReader("milk3.in")));  
  4.             PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("milk3.out")));  
  5.               
  6.             LinkedList<status> list = new LinkedList<status>();//bfs队列  
  7.             HashSet<status> hash = new HashSet<status>();//记录已经产生过的a,b,c三个桶的容量状态  
  8.             HashSet<Integer> result = new HashSet<Integer>();//记录已经产生的c桶的状态  
  9.               
  10.             int a = in.nextInt();  
  11.             int b = in.nextInt();  
  12.             int c = in.nextInt();  
  13.             status init = new status(0,0,c);  
  14.             list.add(init);  
  15.               
  16.             while (list.size()!=0){//编列bfs队列  
  17.                 status temp = list.remove(0);  
  18.                 if (hash.contains(temp)){  
  19.                     //doNothing  
  20.                 } else {  
  21.                     hash.add(temp);  
  22.                     //如果a桶的容量为空,则在结果集当中加入c的状态  
  23.                     if (temp.a==0){  
  24.                         result.add(temp.c);  
  25.                     }  
  26.                     //遍历所有可能的倒牛奶方式  
  27.                     //a->b  
  28.                     if (temp.a >= b-temp.b){  
  29.                         status node = new status(temp.a-b+temp.b,b,temp.c);  
  30.                         if (!hash.contains(node)){  
  31.                             list.add(node);  
  32.                         }  
  33.                     }else{  
  34.                         status node = new status(0,temp.b+temp.a,temp.c);  
  35.                         if (!hash.contains(node)){  
  36.                             list.add(node);  
  37.                         }  
  38.                     }  
  39.                     //a->c  
  40.                     if (temp.a >= c-temp.c){  
  41.                         status node = new status(temp.a-c+temp.c,temp.b,c);  
  42.                         if (!hash.contains(node)){  
  43.                             list.add(node);  
  44.                         }  
  45.                     }else{  
  46.                         status node = new status(0,temp.b,temp.c+temp.a);  
  47.                         if (!hash.contains(node)){  
  48.                             list.add(node);  
  49.                         }  
  50.                     }  
  51.                     //b->a  
  52.                     if (temp.b >= a-temp.a){  
  53.                         status node = new status(a,temp.b-a+temp.a,temp.c);  
  54.                         if (!hash.contains(node)){  
  55.                             list.add(node);  
  56.                         }  
  57.                     }else{  
  58.                         status node = new status(temp.a+temp.b,0,temp.c);  
  59.                         if (!hash.contains(node)){  
  60.                             list.add(node);  
  61.                         }  
  62.                     }  
  63.                     //b->c  
  64.                     if (temp.b >= c-temp.c){  
  65.                         status node = new status(temp.a,temp.b-c+temp.c,c);  
  66.                         if (!hash.contains(node)){  
  67.                             list.add(node);  
  68.                         }  
  69.                     }else {  
  70.                         status node = new status(temp.a,0,temp.c+temp.b);  
  71.                         if (!hash.contains(node)){  
  72.                             list.add(node);  
  73.                         }  
  74.                     }  
  75.                       
  76.                     //c->a  
  77.                     if (temp.c >= a-temp.a){  
  78.                         status node = new status(a,temp.b,temp.c-a+temp.a);  
  79.                         if (!hash.contains(node)){  
  80.                             list.add(node);  
  81.                         }  
  82.                     }else{  
  83.                         status node = new status(temp.a+temp.c,temp.b,0);  
  84.                         if (!hash.contains(node)){  
  85.                             list.add(node);  
  86.                         }  
  87.                     }  
  88.                       
  89.                     //c->b  
  90.                     if (temp.c >= b-temp.b){  
  91.                         status node = new status(temp.a,b,temp.c-b+temp.b);  
  92.                         if (!hash.contains(node)){  
  93.                             list.add(node);  
  94.                         }  
  95.                     }else {  
  96.                         status node = new status(temp.a,temp.b+temp.c,0);  
  97.                         if (!hash.contains(node)){  
  98.                             list.add(node);  
  99.                         }  
  100.                     }  
  101.                       
  102.                 }  
  103.             }  
  104.             Integer[] out = new Integer[result.size()];  
  105.             result.toArray(out);  
  106.             Arrays.sort(out);  
  107.             StringBuilder sb = new StringBuilder();  
  108.             for (int i = 0;i<out.length;i++){  
  109.                 sb.append(out[i]+" ");  
  110.             }  
  111.             sb.deleteCharAt(sb.length()-1);  
  112.             pw.println(sb);  
  113.             pw.close();  
  114.             in.close();  
  115.         } catch (Exception e) {  
  116.             // TODO Auto-generated catch block  
  117.             e.printStackTrace();  
  118.         }  
  119.     }  
  120. }  
  121.   
  122. class status {  
  123.     int a ;  
  124.     int b ;  
  125.     int c ;  
  126.       
  127.     public status(int a ,int b ,int c){  
  128.         this.a = a;  
  129.         this.b = b;  
  130.         this.c = c;  
  131.     }  
  132.       
  133.     @Override  
  134.     public boolean equals(Object obj) {  
  135.         status sta = (status)obj;  
  136.         if (this.a == sta.a && this.b == sta.b && this.c == sta.c){  
  137.             return true;  
  138.         } else {  
  139.             return false;  
  140.         }  
  141.     }  
  142.       
  143.     @Override  
  144.     public int hashCode() {  
  145.         // TODO Auto-generated method stub  
  146.         return a*1 + b*2 + c*3;  
  147.     }  
  148. }
http://jackneus.com/programming-archives/mothers-milk/

Read full article from mother'smilk - codetrick

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts