UVa 10603 - Fill,经典倒水问题+隐式图搜索+dfs - D_Double's Journey - 博客频道 - CSDN.NET


UVa 10603 - Fill,经典倒水问题+隐式图搜索+dfs - D_Double's Journey - 博客频道 - CSDN.NET
类型: 隐式图搜索
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=110&page=show_problem&problem=1544
原题:
There are three jugs with a volume of a, b and c liters. (a, b, and c are positive integers not greater than 200). The first and the second jug are initially empty, while the third
is completely filled with water. It is allowed to pour water from one jug into another until either the first one is empty or the second one is full. This operation can be performed zero, one or more times.

You are to write a program that computes the least total amount of water that needs to be poured; so that at least one of the jugs contains exactly d liters of water (d is a positive integer not greater than 200). If it is not possible to measure d liters this way your program should find a smaller amount of water d' < d which is closest to d and for which d' liters could be produced. When d' is found, your program should compute the least total amount of poured water needed to produce d' liters in at least one of the jugs.

Input

The first line of input contains the number of test cases. In the next T lines, T test cases follow. Each test case is given in one line of input containing four space separated integers - a, b, c and d.

Output

The output consists of two integers separated by a single space. The first integer equals the least total amount (the sum of all waters you pour from one jug to another) of poured water. The second integer equals d, if d liters of water could be produced by such transformations, or equals the closest smaller value d' that your program has found.


样例输入:
2
2 3 4 2
96 97 199 62

样例输出:
2 2
9859 62


题目大意:
有三个杯子它们的容量分别是a,b,c, 并且初始状态下第一个和第二个是空的, 第三个杯子是满水的。可以把一个杯子的水倒入另一个杯子,当然,当被倒的杯子满了或者倒的杯子水完了,就不能继续倒了。
你的任务是写一个程序计算出用最少的倒水量,使得其中一个杯子里有d升水。如果不能倒出d升水的话,那么找到一个d' < d ,使得d' 最接近d。


分析与总结:
因为共有3个水杯, 根据每一杯的水量v1,v2,v3, 可以得到一个状态state(v1,v2,v3); 
为了方便进行dfs搜索的状态转移,可以用两个三维数组volume[3], state[3]分别表示三个杯子的容量和状态。然后会有倒水的动作,可以从第1个杯子倒入第2,3个,从第2个倒入第1,3个等等……所以用两个for循环,可以遍历出所有的倒水方案。
然后注意一些不能倒水的条件,比如要倒的杯子是空的,目标杯子是满的,则不进行倒水的动作。


X. BFS
http://acm.lilingfei.com/uva-10603-fill-%EF%BC%88%E4%BE%8B%E9%A2%987-8%EF%BC%89_41
、vis数组只用开两维
看到讨论中大家都是用的三维数组vis[201][201][201],其实有了两杯水的数据,第三杯水可以用总量减去两杯水的量得到,所以不需要维护3维数组
2、解的存储
因为题目说如果取不到d,就要打印出比d小的最大的可能解d’以及倒水的量,所以bfs就把所有可能的d以及倒水量都存了下来,如果之前取到过这个d,则判断倒水量是否比之前的少,如果满足要求的话就更新数据。最后从d开始往下减小,遇到第一个取到过的解就打印并返回
3、优先队列
首先要注意这道题问的是倒水量最少,而不是倒水次数最少,而这两者没有必然关系。所以在bfs的时候,就不能用普通queue存储需要遍历的节点,而应该用一个优先队列,让倒水量少的排在前头。
另外在讨论中看到很多人用的是dfs,并且很多人得了TLE。然后大家比较推荐的解法是dijkstra。
  1. struct Node {
  2. int v[3], dist;
  3. bool operator < (const Node& n) const {
  4. return dist > n.dist;
  5. }
  6. };
  7. //Global Variables.
  8. int vis[maxn][maxn];
  9. int ans[maxn];
  10. /////
  11. void update_ans(Node& u) {
  12. for(int i = 0; i < 3; i ++) {
  13. int d = u.v[i];
  14. if(ans[d] < 0 || u.dist < ans[d]) ans[d] = u.dist;
  15. }
  16. }
  17. void solve(int a, int b, int c, int d) {
  18. int cap[3] = {a,b,c};
  19. memset(vis, 0, sizeof(vis));
  20. memset(ans, -1, sizeof(ans));
  21. Node startN;
  22. startN.v[0] = startN.v[1] = 0;
  23. startN.v[2] = c;
  24. startN.dist = 0;
  25. priority_queue<Node> q;
  26. q.push(startN);
  27. vis[0][0] = 1;
  28. while(!q.empty()) {
  29. Node u = q.top(); q.pop();
  30. update_ans(u);
  31. for(int i = 0; i < 3; i ++) {
  32. for(int j = 0; j < 3; j ++) if(i != j) {
  33. if(u.v[j] == cap[j] || u.v[i] == 0) continue; //Empty / Full
  34. int amount = min(cap[j] - u.v[j], u.v[i]); //Amount of water to fill
  35. Node newN;
  36. memcpy(&newN, &u, sizeof(u));
  37. newN.v[i] = u.v[i] - amount;
  38. newN.v[j] = u.v[j] + amount;
  39. newN.dist = u.dist + amount;
  40. if(!vis[newN.v[0]][newN.v[1]]) {
  41. q.push(newN);
  42. vis[newN.v[0]][newN.v[1]] = 1;
  43. }
  44. }
  45. }
  46. }
  47. while(d>=0) { //print ans
  48. if(ans[d] >= 0) {
  49. printf("%d %d\n", ans[d], d);
  50. return;
  51. }
  52. d--;
  53. }
  54. }
http://blog.csdn.net/murmured/article/details/18771149
把能达到的状态看成图上的点,进行BFS。
然后我用的是优先队列,能保证最少倒的条件。(按当前倒的水量维护好了)
bool vis[MAXN][MAXN][MAXN];
int state[3],d,ans;
struct node
{
 int state[3];
 int val;
 node(){}
 node(int aa,int bb,int cc,int dd){ state[0]=aa;state[1]=bb;state[2]=cc;val=dd;}
 bool operator <(const node & x)const
 {
  return val>x.val;
 }
};
void bfs()
{
 memset(vis,0,sizeof(vis));
 priority_queue<node> q;
 q.push(node(0,0,state[2],0));
 vis[0][0][state[2]]=true;
 while(!q.empty())
 {
  node cur=q.top();
  q.pop();

  if(cur.state[0]==d || cur.state[1]==d || cur.state[2]==d)
  {
   ans=cur.val;
   return;
  }

  for(int i=0;i<3;i++)
  {
   for(int j=0;j<3;j++)        //j往i倒水
   {
    if(i==j) continue;     //不能自己给自己倒水
    if(!cur.state[j]) continue; //为空不行
    node temp;
    int *t=temp.state;   //用指针优化下可读性  就是说t和temp.state是一个数组
    if(cur.state[j] + cur.state[i] > state[i]) //超过了容量,只能倒满
    {
     t[i]=state[i];
     t[j]=cur.state[j] + cur.state[i] -state[i];
     t[3-i-j]=cur.state[3-i-j];       //3=0+1+2 所以减去代表剩下的那个
     temp.val=cur.val+state[i] - cur.state[i];
    }
    else
    {
     t[i]=cur.state[j] + cur.state[i];
     t[j]=0;
     t[3-i-j]=cur.state[3-i-j];  
     temp.val=cur.val+cur.state[j];
    }
    if(!vis[ t[0] ][ t[1] ][ t[2] ])  //没访问过才加入队列
    {
     vis[ t[0] ][ t[1] ][ t[2] ]=true;
     q.push(temp);
    }
   }
  }

 }
}
  ans=INF;
  scanf("%d%d%d%d",&state[0],&state[1],&state[2],&d);
  bfs();
  while(ans==INF)
  {
   d--;   
   bfs();
  }
  printf("%d %d\n",ans,d);
Same solution: http://blog.csdn.net/chenguolinblog/article/details/7829360
http://morris821028.github.io/2014/05/05/oj/uva/uva-10603/
http://ng1091.com/blog/archives/291
Read full article from UVa 10603 - Fill,经典倒水问题+隐式图搜索+dfs - D_Double's Journey - 博客频道 - CSDN.NET

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