UVA10603 FILL(宽搜)
There are three jugs with a volume of a, b and c liters. (a, b, and c are positive integers not greater than 200). The first and the second jug are initially empty, while the third is completely filled with water. It is allowed to pour water from one jug into
another until either the first one is empty or the second one is full. This operation can be performed zero, one or more times.
You are to write a program that computes the least total amount of water that needs to be poured; so that at least one of the jugs contains exactly d liters of water (d is a positive integer not greater than 200). If it is not possible to measure d liters this
way your program should find a smaller amount of water d′ < d which is closest to d and for which d′ liters could be produced. When d′ is found, your program should compute the least total amount of poured water needed to produce d′ liters in at least one of
the jugs.
Input
The first line of input contains the number of test cases. In the next T lines, T test cases follow. Each test case is given in one line of input containing four space separated integers — a, b, c and d.
Output
The output consists of two integers separated by a single space. The first integer equals the least total amount (the sum of all waters you pour from one jug to another) of poured water. The second integer equals d, if d liters of water could be produced by
such transformations, or equals the closest smaller value d′ that your program has found.
Sample Input
2 2 3 4 2 96 97 199 62
Sample Output
2 2 9859 62
首先是状态数量的判断:a有(a+1)种,b有(b+1)种,而且a,b<200,所以最多201*201种状态,用搜索是可以的。
为了找到最少的水的量(不是步数),定义一个节点包含当前水的数量,用优先队列来实现最短路。
书上说和Dijkstra很像,还真的是这样,图的算法和这种搜索的算法有着某种神秘的联系。
是否可以把倒水看成在图中走一步,该边的权值就是水量?贪心的往下走?
#include <bits/stdc++.h>
using namespace std;
#define N 205
struct Node{
int v[3], dist;
bool operator < (const Node &a)const{
return dist > a.dist;
}
};
int ans[N * N], cap[3];
bool vis[N][N];
void solve(int a, int b, int c, int d)
{
memset(vis, 0, sizeof(vis));
memset(ans, -1, sizeof(ans));
priority_queue< Node, vector<Node> > que;
Node s;
cap[0] = a;cap[1] = b;cap[2] = c;
s.v[0] = s.v[1] = 0;s.v[2] = c;
s.dist = 0;
que.push(s);
while(!que.empty()){
Node h = que.top();que.pop();
for(int i = 0; i < 3; i++){
if(ans[h.v[i]] < 0 || ans[h.v[i]] > h.dist){
ans[h.v[i]] = h.dist;
}
}
if(ans[d] >= 0)
break;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++){
if(i != j && h.v[i] > 0 && h.v[j] < cap[j]){
int amount = min(cap[j], h.v[i] + h.v[j]) - h.v[j];
Node tmp;
memcpy(&tmp, &h, sizeof(h));
tmp.dist = h.dist + amount;
tmp.v[i] -= amount;tmp.v[j] += amount;
if(!vis[tmp.v[0]][tmp.v[1]]){
vis[tmp.v[0]][tmp.v[1]] = true;
que.push(tmp);
}
}
}
}
while(d >= 0){
if(ans[d] >= 0){
printf("%d %d\n", ans[d], d);
return;
}
d--;
}
}
int main()
{
int t, a, b, c, d;
scanf("%d", &t);
while(t--){
scanf("%d%d%d%d", &a, &b, &c, &d);
solve(a, b, c, d);
}
return 0;
}
上一篇: 牛客网湘潭大学程序设计竞赛F题:maze
下一篇: 备战蓝桥杯决赛----坚持第六天!!!