题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1495
7 4 3 4 1 3 0 0 0
NO 3
代码如下:
#include <cstdio> #include <cstring> #include<iostream> #include<algorithm> #include<queue> using namespace std; #define MAXN 117 bool vis[MAXN][MAXN]; int s, n, m; struct node { int x,y,all; //x,y,all分别表示n,m,s杯中可乐现有的体积 int t; //步数 }; void BFS() { queue<node> Q; memset(vis,false,sizeof(vis)); node p,q; p.x = 0,p.y = 0,p.t = 0,p.all = s; Q.push(p); vis[p.x][p.y] = true; while(!Q.empty()) { p = Q.front(); Q.pop(); if(p.x == p.all && p.x == s/2) { printf("%d\n",p.t); return; } if(p.all+p.x > n) //s倒n { q.x = n,q.y = p.y,q.all = p.all+p.x-n,q.t = p.t+1; if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } else { q.x = p.all+p.x,q.y = p.y,q.all = 0,q.t = p.t+1; if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } if(p.all+p.y > m) //s倒m { q.x = p.x, q.y = m, q.all = p.all+p.y-m,q.t = p.t+1; if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } else { q.x = p.x,q.y = p.all+p.y,q.all = 0,q.t = p.t+1; if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } if(p.x+p.y > m) //n倒m { q.x = p.x+p.y-m,q.y = m,q.all = p.all,q.t = p.t+1; if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } else { q.x = 0,q.y = p.x+p.y,q.all = p.all,q.t = p.t+1; if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } if(p.x+p.y > n) { q.y = p.y+p.x-n,q.x = n,q.all = p.all,q.t = p.t+1;//m倒n if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } else { q.x = p.x+p.y,q.y = 0,q.all = p.all,q.t = p.t+1; if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } q.all = p.all+p.x,q.x = 0,q.y = p.y,q.t = p.t+1; //n倒s if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } q.all = p.all+p.y,q.x = p.x,q.y = 0,q.t = p.t+1; //m倒s if(!vis[q.x][q.y]) { Q.push(q); vis[q.x][q.y] = true; } } printf("NO\n"); } int main() { while(~scanf("%d%d%d",&s,&n,&m)) { if(s==0 && n==0 && m==0) break; if(s%2) { printf("NO\n"); continue; } if(n < m) { int t = n; n = m; m = t; } BFS(); } return 0; }
原文地址:http://blog.csdn.net/u012860063/article/details/39202657