简单搜索:poj3414
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单搜索:poj3414相关的知识,希望对你有一定的参考价值。
Pots
题意:两个容器,容量A,B,进行倒水操作,求最少的操作次数使得某一容器水量为C。
思路:一个多月前写的时候是没思路的,但是随着搜索算法的学习,慢慢懂得了一些 状态 的问题。这里,倒水就有很多的状态比如(FILL(A),B)(A, FILL(B))等。意识到这个之后,因为要求的是最少的操作次数,所以用bfs,注意剪枝。代码如下:
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 #include <vector> 5 using namespace std; 6 7 int A, B, C; 8 int hashed[11000]; 9 10 struct Node { 11 int la, lb; 12 int step; 13 vector<int>path; 14 }; 15 16 const char *Path[] = {"HAHA\0", "DROP(1)\0", "DROP(2)\0", "FILL(1)\0", "FILL(2)\0", 17 "POUR(1,2)\0", "POUR(2,1)\0"}; 18 19 bool is_ok(Node node) 20 { 21 int idx = node.la * 100 + node.lb; 22 if (hashed[idx] == 1) 23 return false; 24 hashed[idx] = 1; 25 return true; 26 } 27 28 int bfs() 29 { 30 queue<Node>Q; 31 Node node; 32 node.la = 0, node.lb = 0, node.path.clear(), node.step = 0; 33 Q.push(node); 34 35 while (!Q.empty()) { 36 Node now = Q.front(); Q.pop(); 37 if (now.la == C || now.lb == C) { 38 printf("%d\n", now.step); 39 for (vector<int>::iterator it = now.path.begin(); it != now.path.end(); it++) { 40 printf("%s\n", Path[*it]); 41 } 42 return 1; 43 } 44 for (int i = 1; i <= 6; i++) { 45 if (i == 1) { 46 Node next = now; 47 next.la = 0, next.lb = now.lb, next.path.push_back(i), next.step = now.step + 1; 48 if (next.lb != 0 && is_ok(next)) 49 Q.push(next); 50 } 51 if (i == 2) { 52 Node next = now; 53 next.la = now.la, next.lb = 0, next.path.push_back(i), next.step = now.step + 1; 54 if (next.la != 0 && is_ok(next)) 55 Q.push(next); 56 } 57 if (i == 3) { 58 Node next = now; 59 next.la = A, next.lb = now.lb, next.path.push_back(i), next.step = now.step + 1; 60 if (is_ok(next)) 61 Q.push(next); 62 } 63 if (i == 4) { 64 Node next = now; 65 next.la = now.la, next.lb = B, next.path.push_back(i), next.step = now.step + 1; 66 if (is_ok(next)) 67 Q.push(next); 68 } 69 if (i == 5) { 70 Node next = now; 71 int su = now.la + now.lb; 72 if (su >= B) { 73 next.la = su - B, next.lb = B, next.path.push_back(i), next.step = now.step + 1; 74 if (is_ok(next)) 75 Q.push(next); 76 } else { 77 next.la = 0, next.lb = su, next.path.push_back(i), next.step = now.step + 1; 78 if (is_ok(next)) 79 Q.push(next); 80 } 81 } 82 if (i == 6) { 83 Node next = now; 84 int su = now.la + now.lb; 85 if (su >= A) { 86 next.la = A, next.lb = su - A, next.path.push_back(i), next.step = now.step + 1; 87 if (is_ok(next)) 88 Q.push(next); 89 } else { 90 next.la = su, next.lb = 0, next.path.push_back(i), next.step = now.step + 1; 91 if (is_ok(next)) 92 Q.push(next); 93 } 94 } 95 } 96 } 97 return -1; 98 } 99 100 int main() 101 { 102 scanf("%d%d%d", &A, &B, &C); 103 int ans = bfs(); 104 if (ans == -1 ) { 105 printf("impossible\n"); 106 } 107 return 0; 108 }
以上是关于简单搜索:poj3414的主要内容,如果未能解决你的问题,请参考以下文章