1169: PIPI倒水
题目描述
PIPI有三个杯子,容量分别为 a ,b ,c,最初只有第三个杯子有c升水,其余两个杯子都是空的,PIPI想知道至少要倒出多少升水才能够让某一个杯子中的水有 d 升,如果无法做到恰好 d 升,就让某个杯子中的水是 d’ 升,d’<d且尽可能接近 d。(由于杯子没刻度,所以我们一个杯子往另一个杯子倒水时,要么将倒出的杯子的水倒空,要么将倒入的杯子倒满)
输入
第一行包含一个正整数T,代表测试用例组数。
每一组输入四个整数 a ,b ,c, d。分别表示三个杯子的容量以及目标水量d . (1<=a,b,c,d<=200)
输出
对于每一组输入,输出最少的倒水量和目标水量。(d或者d’)
样例输入
2
2 3 4 2
96 97 199 62
样例输出
2 2
9859 62
思路
题意是想尽可能地少倒水,使得某个杯子中出现最接近目标的水量。因为每次倒水量是不确定的,如果采用普通的 BFS 可能得不到正确的解,所以要使用优先队列,优先访问倒水量少的状态。此题还有一个关键是使用数组(ans)记录任意一个杯子中水量为 t 时的最少倒水量(ans[t]),这样才能找到尽可能接近 d 的解。
#include<bits/stdc++.h>
using namespace std;
const int N = 200 + 5;
bool vis[N][N];//已知 a,b 杯中的水量和总水量可确定 c 杯中水量,所以标记数组只需二维
int ans[N];//ans[i]--代表任意水杯水量为 i 时,所需的最小倒水量
typedef struct node
{
int cup[3], t;// t--当前状态倒水量
// 根据倒水量建立小根堆
bool operator<(const node &o)const{
return t > o.t;
}
}node;
int main()
{
// freopen("in.cpp", "r", stdin);
int T, cup[3], d;
scanf("%d", &T);
while(T--)
{
scanf("%d%d%d%d", &cup[0], &cup[1], &cup[2], &d);
memset(vis, false, sizeof(vis));
memset(ans, -1, sizeof(ans));
//初始时只有 c 杯有水且杯满
vis[0][0] = true;
ans[cup[2]] = 0;
priority_queue<node> q;
q.push({0, 0, cup[2], 0});
node p;
while(!q.empty())
{
p = q.top();
q.pop();
for(int i = 0; i < 3; i++)
{
if(ans[p.cup[i]] == -1)
ans[p.cup[i]] = p.t;
}
if(ans[d] != -1)
break;
//模拟六种倒水方式,i 倒给 j
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
if(i == j) continue;//自己给自己倒
int pour = min(p.cup[i], cup[j] - p.cup[j]);// 倒水量取 倒空 和 加满 中的较小值
node nxt = p;
nxt.cup[i] -= pour;
nxt.cup[j] += pour;
nxt.t += pour;
if(!vis[nxt.cup[0]][nxt.cup[1]])
{
vis[nxt.cup[0]][nxt.cup[1]] = true;
q.push(nxt);
}
}
}
}
// 从 d 开始往前遍历 ans 数组寻找最接近 d 的答案
for(int i = d; i > 0; i--)
{
if(ans[i] != -1)
{
printf("%d %d\n", ans[i], i);
break;
}
}
}
return 0;
}