POJ 3414 Pots(简单模拟+dfs)

125 篇文章 0 订阅
19 篇文章 0 订阅

Description
给你两个容器,求出获得指定量水的步骤
三个操作
FILL(A):将A容器装满水
DROP(A):将A容器中的水倒出
POUR(A,B):将A容器中的水全部倒入B容器中
Input
每组用例包括三个整数A,B,C,以文件尾结束输入
Output
对于每组用例,输出获得C体积水的步骤,如果不存在可行解则输出impossible
Sample Input
3 5 4
Sample Output
6
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)
Solution
简单模拟+dfs
每次最多有六种情况,填满a,填满b,清空a,清空b,从a倒到b,从b倒到a。对每种情况将在这种情况下的可能的情况进入队列,直到找到最终结果
注意:倒的方法可能有多种,由于是special judge,所以输出任意一种可行解即可
Code

#include <iostream>
#include <queue>
#include <map>
#include <string>
#include <cmath>
using namespace std;
struct Data
{
    int x,y; 
    string s;
    bool operator <(Data b) const
    {
        if(x!=b.x) return x<b.x;
        return y<b.y;
    }
};
int main()
{
    int A,B,C,sum;
    Data t,temp;
    cin>>A>>B>>C;
    t.x=t.y=0;//初始状态两桶中均没水 
    temp.x=-1;
    queue<Data> Q;
    map<Data,Data> M;//储存操作队列 
    while(!Q.empty())//清空队列 
        Q.pop();
    Q.push(t); 
    M[t]=temp;
    while(!Q.empty())
    {
        t=Q.front(); 
        Q.pop();
        if(t.x==C||t.y==C)//遇到可行解 
            break;
        temp.x=A; 
        temp.y=t.y; 
        temp.s="FILL(1)";//填满A 
        if(M.find(temp)==M.end()) 
            Q.push(temp),M[temp]=t;     
        temp.x=t.x; 
        temp.y=B; 
        temp.s="FILL(2)";//填满B 
        if(M.find(temp)==M.end()) 
            Q.push(temp),M[temp]=t;     
        temp.x=0; 
        temp.y=t.y; 
        temp.s="DROP(1)";//清空A 
        if(M.find(temp)==M.end()) 
            Q.push(temp),M[temp]=t;     
        temp.x=t.x; 
        temp.y=0; 
        temp.s="DROP(2)";//清空B 
        if(M.find(temp)==M.end()) 
            Q.push(temp),M[temp]=t;     
        temp.x=min(t.x+t.y,A);
        temp.y=max(0,t.y-A+t.x); 
        temp.s="POUR(2,1)";//B倒A 
        if(M.find(temp)==M.end()) 
            Q.push(temp),M[temp]=t;
        temp.x=max(0,t.x-B+t.y);
        temp.y=min(t.x+t.y,B); 
        temp.s="POUR(1,2)";//A倒B 
        if(M.find(temp)==M.end()) 
            Q.push(temp),M[temp]=t;
    }
    if(t.x==C||t.y==C)
    {
        string ans=""; 
        sum=0;
        for(temp=t;temp.x||temp.y;temp=M[temp]) 
            ans=temp.s+"\n"+ans,sum++;
        cout<<sum<<endl<<ans;//按格式输出 
    }
    else 
        cout<<"impossible"<<endl;//按格式输出 
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值