//yy:昨天看着这题突然有点懵,不知道怎么记录路径,然后交给房教了,,,然后默默去写另一个bfs,想清楚思路后花了半小时写了120+行的代码然后出现奇葩的CE,看完FAQ改了之后又WA了。然后第一次用对拍去找特殊数据折腾到十二点半终于AC,最后只想感叹没有仔细读题,没办法啊看着英语略烦躁,不扯了,那个题题解不想写了,回到这题。。。今天中午还是花了四十分钟写了这题(好慢啊orz),感觉,啊为什么别人可以一下子就写出来,我却想不到怎么写呢!!!
题意:两个给定容量a, b的杯子,有倒满水,倒光水,互相倒水三个操作,直到任意一个杯子中的水达到指定容量c为止。输出操作步骤。(a,b,c≤100)
题解:六个方向的bfs,加上100*100的记录路径。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 #include <queue> 6 #define CLR(a,b) memset((a),(b),sizeof((a))) 7 using namespace std; 8 typedef long long ll; 9 const int inf = 0x3f3f3f3f; 10 const int N = 105; 11 string s[] = {"impossible","FILL(1)","FILL(2)","DROP(1)","DROP(2)","POUR(1,2)","POUR(2,1)"}; 12 int a, b, c; 13 typedef struct Node { 14 int x, y; 15 Node(int _x = 0, int _y = 0):x(_x),y(_y){} 16 }node; 17 node g[N][N];//存储上一步的状态 18 int Do[N][N];//记录操作 19 bool vis[N][N];//标记 20 node bfs() { 21 CLR(g, -1); CLR(vis, 0); 22 node t; 23 int i = 0, j = 0; 24 queue<node> q; 25 q.push(Node(0, 0)); 26 while(!q.empty()) { 27 t = q.front(); q.pop(); 28 if(t.x == c || t.y == c) return t; 29 vis[t.x][t.y] = 1; 30 if(t.x != a && !vis[a][t.y]) { q.push(Node(a, t.y)); Do[a][t.y] = 1; g[a][t.y] = t; } 31 if(t.y != b && !vis[t.x][b]) { q.push(Node(t.x, b)); Do[t.x][b] = 2; g[t.x][b] = t; } 32 if(t.x && !vis[0][t.y]) { q.push(Node(0, t.y)); Do[0][t.y] = 3; g[0][t.y] = t; } 33 if(t.y && !vis[t.x][0]) { q.push(Node(t.x, 0)); Do[t.x][0] = 4; g[t.x][0] = t; } 34 if(!vis[i = max(0, t.x + t.y - b)][j = min(b, t.x + t.y)]) { q.push(Node(i, j)); Do[i][j] = 5; g[i][j] = t; } 35 if(!vis[i = min(a, t.x + t.y)][j = max(0, t.x + t.y - a)]) { q.push(Node(i, j)); Do[i][j] = 6; g[i][j] = t; } 36 } 37 return Node(0, 0); 38 } 39 void dfs(const node & d, const int & p) { 40 if(d.x + d.y == 0) { 41 if(p) { cout << p << endl; } else { cout << s[0] << endl; } 42 return; 43 } 44 dfs(g[d.x][d.y], p+1); 45 cout << s[Do[d.x][d.y]] << endl; 46 } 47 int main() { 48 scanf("%d%d%d", &a, &b, &c); 49 node ans = bfs(); 50 dfs(ans, 0); 51 return 0; 52 }