UVA 10603 倒水问题

因为要求某一个水量为D的时候的最少倒水总量,很显然是一道BFS

既可以模拟六种倒水何况

在过程中进行定界,对越界的进行剪枝

dp数组就起到了这个作用,同时res数组是决定最终结果而设立的一个数组。同时配和dp进行剪枝。

ac代码:

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>

using namespace std;

#define INF 0x3f3f3f3f

const int N=205;

int dp[N][N][N],res[N];
int A,B,C,D;
queue<int> qa,qb,qc,qt;

void pushnode(int a,int b,int c,int tot){
    qa.push(a);qb.push(b);qc.push(c);qt.push(tot);
}

void update(int a,int b,int c,int tot){
    if(dp[a][b][c]<=tot) return ;
    if(tot>=res[D]) return;
    dp[a][b][c]=tot;
    res[a]=min(res[a],tot);
    res[b]=min(res[b],tot);
    res[c]=min(res[c],tot);
    if(a<B-b) pushnode(0,a+b,c,tot+a);
    else pushnode(a-(B-b),B,c,tot+B-b);
    if(a<C-c) pushnode(0,b,c+a,tot+a);
    else pushnode(a-(C-c),b,C,tot+C-c);
    if(b<A-a) pushnode(a+b,0,c,tot+b);
    else pushnode(A,b-(A-a),c,tot+A-a);
    if(b<C-c) pushnode(a,0,c+b,tot+b);
    else pushnode(a,b-(C-c),C,tot+C-c);
    if(c<A-a) pushnode(a+c,b,0,tot+c);
    else pushnode(A,b,c-(A-a),tot+A-a);
    if(c<B-b) pushnode(a,c+b,0,tot+c);
    else pushnode(a,B,c-(B-b),tot+B-b);
}

void bfs(int a,int b,int c,int tot){
    qa.push(a);qb.push(b);qc.push(c);qt.push(tot);
    while(!qa.empty()){
        a=qa.front();qa.pop();
        b=qb.front();qb.pop();
        c=qc.front();qc.pop();
        tot=qt.front();qt.pop();
        update(a,b,c,tot);
    }
}

int main(){
    int cs;
    ios::sync_with_stdio(false);cin.tie(0);
    cin>>cs;
    while(cs--){
        cin>>A>>B>>C>>D;
        for(int i=0;i<=A;i++){
            for(int j=0;j<=B;j++){
                for(int k=0;k<=C;k++){
                    dp[i][j][k]=INF;
                }
            }
        }
        for(int i=0;i<=D;i++){
            res[i]=INF;
        }
        bfs(0,0,C,0);
        while(res[D]==(int)INF) D--;
        cout<<res[D]<<" "<<D<<endl;
    }
    return 0;
}
/*
2
2 3 4 2
96 97 199 62
*/

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/81175358