kuangbin带你飞]专题一 简单搜索 H

166 篇文章 0 订阅
32 篇文章 0 订阅

http://poj.org/problem?id=3414
You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
1 FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
2 DROP(i) empty the pot i to the drain;
3 POUR(i,j) pour from pot i to pot j; after this operation either the pot j is full (and there may be some water left in the pot i), or the pot i is empty (and all its contents have been moved to the pot j).
Write a program to find the shortest possible sequence of these operations that will yield exactly C liters of water in one of the pots.

题意:

两个杯子容量A B
操作:装满其中一个,倒空其中一个,把一个杯子的水倒到另一个杯子(倒慢另一个或者倒空自己为止)

tip

bfs走一下。。。主要的是记录路径。。我分了两个数组,一个记录从上个到现在这个的操作是什么,另一个记录上一步的状态是什么。。
vis【】【】,表示两个杯子分别的装水量,不可能重复

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int,int> pii;
const int maxn = 1100;
int A,B,C,step[maxn][maxn],an[maxn];
bool vis[maxn][maxn];
pii pre[maxn][maxn];

pii sov(int step,int x,int y){
    if(step == 1)   x = A;
    if(step == 2)   y = B;
    if(step == 3)   x = 0;
    if(step == 4)   y = 0;
    if(step == 5){
        int ans = min(A-x,y);
        x += ans;y-=ans;
    }
    if(step == 6){
        int ans = min(x,B-y);
        x -= ans;y += ans;
    }
    return make_pair(x,y);
}

void pr(int step){
    if(step == 1)   printf("FILL(1)\n");
    if(step == 2)   printf("FILL(2)\n");
    if(step == 3)   printf("DROP(1)\n");
    if(step == 4)   printf("DROP(2)\n");
    if(step == 5)   printf("POUR(2,1)\n");
    if(step == 6)   printf("POUR(1,2)\n");
}

void print(int x,int y){
    int tot = 0;
    while(!(x==0&&y==0)){
        an[tot++] = step[x][y];
        pii tmp = pre[x][y];
        x = tmp.first;y = tmp.second;
    }
    printf("%d\n",tot);
    for(int i = tot-1 ; i >= 0 ;i--){
        pr(an[i]);
    }
}

void bfs(){
    queue<pii>q;
    q.push(make_pair(0,0));

    while(!q.empty()){
        pii tmp = q.front();
        q.pop();
        if(tmp.first == C||tmp.second == C){
            print(tmp.first,tmp.second);
            return;
        }
        for(int i = 1 ; i <= 6 ; i++){
            pii s = sov(i,tmp.first,tmp.second);
           // printf("s.fi = %d , s.se = %d\n",s.first,s.second);
            if(vis[s.first][s.second] == false){
                vis[s.first][s.second] = true;
                q.push(s);
                pre[s.first][s.second] = tmp;
                step[s.first][s.second] = i;
            }
        }
    }
    printf("impossible\n");
}

void init(){
    memset(vis,false,sizeof(vis));
    vis[0][0] = true;
    bfs();
}

int main(){
    while(~scanf("%d%d%d",&A,&B,&C))
        init();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值