标签:
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 using namespace std; 7 8 const int MAXHASHSIZE = 500; 9 int d, _head[MAXHASHSIZE], _next[MAXHASHSIZE]; 10 int vol[3], _d, ans, idx, st[MAXHASHSIZE], pour_set[MAXHASHSIZE]; 11 12 struct Node { 13 int v[3], pour; 14 Node(int a = 0, int b = 0, int c = 0, int p = 0) { 15 v[0] = a; v[1] = b; v[2] = c; pour = p; 16 } 17 bool operator == (const Node &rhs) const { 18 for (int i = 0; i < 3; i++) if (rhs.v[i] != v[i]) return false; 19 if (rhs.pour != pour) return false; 20 return true; 21 } 22 }; 23 24 void init() { 25 _d = -1; 26 ans = 2147483647; 27 idx = 1; 28 memset(_head, 0, sizeof(_head)); 29 } 30 31 bool try_to_insert(Node &cur) { 32 int status = cur.v[0] * 1000000 + cur.v[1] * 1000 + cur.v[2]; 33 int h = status % MAXHASHSIZE; 34 int u = _head[h]; 35 while (u) { 36 if (st[u] == status) { 37 if (cur.pour < pour_set[u]) { 38 pour_set[u] = cur.pour; 39 return 1; 40 } 41 return 0; 42 } 43 u = _next[u]; 44 } 45 st[idx] = status; 46 pour_set[idx] = cur.pour; 47 _next[idx] = _head[h]; 48 _head[h] = idx++; 49 return 1; 50 } 51 52 void bfs(Node start) { 53 pour_set[1] = start.pour; 54 try_to_insert(start); 55 queue<Node> q; 56 q.push(start); 57 while (!q.empty()) { 58 Node cur = q.front(); q.pop(); 59 for (int i = 0; i < 3; i++) { 60 if (cur.v[i] == _d) 61 ans = min(ans, cur.pour); 62 else if (cur.v[i] > _d && cur.v[i] <= d) { 63 ans = cur.pour; 64 _d = cur.v[i]; 65 } 66 if (cur.v[i] != 0) 67 for (int j = 0; j < 3; j++) if (i != j) { 68 int pour = min(cur.v[i], vol[j] - cur.v[j]); 69 cur.v[i] -= pour; 70 cur.v[j] += pour; 71 Node nextn = Node(cur.v[0], cur.v[1], cur.v[2], cur.pour + pour); 72 cur.v[i] += pour; 73 cur.v[j] -= pour; 74 if (try_to_insert(nextn)) q.push(nextn); 75 } 76 } 77 } 78 } 79 80 int main() { 81 int T; 82 scanf("%d", &T); 83 while (T--) { 84 init(); 85 scanf("%d%d%d%d", &vol[0], &vol[1], &vol[2], &d); 86 bfs(Node(0, 0, vol[2], 0)); 87 printf("%d %d\n", ans, _d); 88 } 89 return 0; 90 }
Fill-倒水问题(Uva-10603-隐式图路径寻找问题)
标签:
原文地址:http://www.cnblogs.com/Bowen-/p/4947158.html