您的位置:首页 > 其它

poj 1606 Jugs (bfs)

2012-03-17 22:05 417 查看
http://poj.org/problem?id=1606

猛一看没思路,仔细想想,记住当前a,b水量及操作就可以bfs了,纯粹的暴力啊。。

输出需要路径,要在node中用指针记录当前状态的前一状态,根据oper输出即可。

code:

#include<cstdio>
#include<cstring>
int a, b, n, h, r ;
bool vis[1001][1001] ;
int ans[100001] ;
struct node{
int va, vb, oper, pre ;
}queue[1000001] ;
void output(){
int i = 1 ;
ans[0] = queue[h].oper ;
h = queue[h].pre ;
while(h){
ans[i++] = queue[h].oper ;
h = queue[h].pre ;
}
for(int j=i-1; j>=0; j--){
switch(ans[j]){
case 1: printf("fill A\n") ;break ;
case 2: printf("fill B\n") ;break ;
case 3: printf("empty A\n") ;break ;
case 4: printf("empty B\n") ;break ;
case 5: printf("pour A B\n") ;break ;
case 6: printf("pour B A\n") ;break ;
}
}
printf("success\n") ;
}
void bfs(){
h = r = 0 ;
queue[r].va = 0 ;
queue[r++].vb = 0 ;
while(h!=r){
node t ;
if(queue[h].vb==n){
output() ;
return ;
}
t.va = a ;
t.vb = queue[h].vb ;
if(!vis[t.va][t.vb]){
vis[t.va][t.vb] = true ;
t.oper = 1 ;
t.pre = h ;
queue[r++] = t ;
}

t.va = queue[h].va ;
t.vb = b ;
if(!vis[t.va][t.vb]){
vis[t.va][t.vb] = true ;
t.oper = 2 ;
t.pre = h ;
queue[r++] = t ;
}

t.va = 0 ;
t.vb = queue[h].vb ;
if(!vis[t.va][t.vb]){
vis[t.va][t.vb] = true ;
t.oper = 3 ;
t.pre = h ;
queue[r++] = t ;
}

t.va = queue[h].va ;
t.vb = 0 ;
if(!vis[t.va][t.vb]){
vis[t.va][t.vb] = true ;
t.oper = 4 ;
t.pre = h ;
queue[r++] = t ;
}

if(queue[h].va-(b-queue[h].vb)<0){
t.va = 0 ;
t.vb = queue[h].vb + queue[h].va ;
}
else{
t.va = queue[h].va-(b-queue[h].vb) ;
t.vb = b ;
}
if(!vis[t.va][t.vb]){
vis[t.va][t.vb] = true ;
t.oper = 5 ;
t.pre = h ;
queue[r++] = t ;
}

if(queue[h].vb-(a-queue[h].va)<0){
t.vb = 0 ;
t.va = queue[h].va + queue[h].vb ;
}
else{
t.vb = queue[h].vb-(a-queue[h].va) ;
t.va = a ;
}
if(!vis[t.va][t.vb]){
vis[t.va][t.vb] = true ;
t.oper = 6 ;
t.pre = h ;
queue[r++] = t ;
}

h ++ ;
}
}
int main(){
while(~scanf("%d%d%d", &a, &b, &n)){
memset(vis, false, sizeof(vis)) ;
bfs() ;
}
return 0 ;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: