UVa 10603:Fill(BFS)

来源:互联网 发布:衣服淘宝文案描述 编辑:程序博客网 时间:2024/06/05 16:21

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=841&page=show_problem&problem=1544

题意:设3个杯子的容量分别为a,b,c,最初只有第3个杯子装满了c升水,其他两个杯子为空。最少需要倒多少升水才能让某一个杯子中的水有d升呢?如果无法做到恰好d升,就让某一个杯子中的水是d’升,其中d<d并且尽量接近d。(1a,b,c,d,200)。要求输出最少的倒水量和目标水量(d或者d’)。

分析:
       将杯子中的水作为状态进行BFS,由于题目要求倒水量最少,所以BFS的队列可以采用优先队列。

代码:

#include <iostream>#include <algorithm>#include <fstream>#include <cstring>#include <vector>#include <queue>#include <cmath>#include <cctype>#include <stack>#include <set>using namespace std;const int maxn = 200 + 5;struct Node{    int dist;    int x[4];    bool operator < (const Node& right) const    {        return dist > right.dist;    }};int T, d;int cap[4], ans[maxn];int v[maxn][maxn];Node tmp, ttmp;void update_ans(const Node& a){    for (int i = 0; i < 3; ++i)        if (ans[a.x[i]] < 0 || a.dist < ans[a.x[i]])            ans[a.x[i]] = a.dist;}void BFS(){    memset(ans, -1, sizeof(ans));    memset(v, 0, sizeof(v));    priority_queue< Node > pq;    tmp.x[0] = 0;    tmp.x[1] = 0;    tmp.x[2] = cap[2];    tmp.dist = 0;    pq.push(tmp);    v[0][0] = 1;    while (!pq.empty())    {        tmp = pq.top();        pq.pop();        update_ans(tmp);        if (ans[d] >= 0)            break;        for (int i = 0; i < 3; ++i)            for (int j = 0; j < 3; ++j)                if (i != j && tmp.x[i] != 0 && tmp.x[j] != cap[j])                {                    int pour = min(tmp.x[i], cap[j] - tmp.x[j]);                    memcpy(&ttmp, &tmp, sizeof(tmp));                    ttmp.dist += pour;                    ttmp.x[i] -= pour;                    ttmp.x[j] += pour;                    if (!v[ttmp.x[0]][ttmp.x[1]])                    {                        v[ttmp.x[0]][ttmp.x[1]] = 1;                        pq.push(ttmp);                    }                }    }    while (d >= 0)    {        if (ans[d] >= 0)        {            printf("%d %d\n", ans[d], d);            return;        }        --d;    }}int main(){    scanf("%d", &T);    for (int C = 0; C < T; ++C)    {        scanf("%d%d%d%d", &cap[0], &cap[1], &cap[2], &d);        BFS();    }    return 0;}
0 0
原创粉丝点击