问题描述:
设3个杯子的容量分别为a,b,c最初只有第3个杯子装满了c升水,其他两个杯子为空。最少需要倒多少升水才能让某一个杯子中的水有d升?如果无法做到恰好d升,就让某一个杯子里的水是d1升其中d1<d并且尽量接近d。(1<=a,b,c,d<=200)。要求输出最少的倒水量和目标水量。
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main{
static int maxn = 200 +5;
static int[][] vis = new int[maxn][maxn];
static int[] ans = new int[maxn];
static int[] cap = new int[3];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
while (T-- > 0) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();
int d = scanner.nextInt();
solve(a, b, c, d);
}
}
public static void solve(int a, int b, int c, int d) {
cap[0] = a; cap[1] = b; cap[2] = c;
init(vis);
init(ans);
PriorityQueue<Nod> queue = new PriorityQueue<>(new Comparator<Nod>() {
@Override
public int compare(Nod o1, Nod o2) {
return o1.dist - o2.dist;
}
});
Nod start = new Nod();
start.dist = 0;
start.v[0] = 0; start.v[1] = 0; start.v[2] = c;
queue.add(start);
vis[0][0] = 1;
while (!queue.isEmpty()) {
Nod u = queue.poll();
updateAns(u);
if (ans[d] >= 0) break;
//i杯向j杯里倒水
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) if (i != j) {
if (u.v[i] == 0 || u.v[j] == cap[j]) continue;
int amount = Math.min(cap[j], u.v[i] + u.v[j]) - u.v[j];
Nod u2 = new Nod();
u2.dist = u.dist;
for (int k = 0; k< 3; k++) {
u2.v[k] = u.v[k];
}
u2.dist = u.dist + amount;
u2.v[i] -= amount;
u2.v[j] += amount;
if (vis[u2.v[0]][u2.v[1]] == 0) {
vis[u2.v[0]][u2.v[1]] = 1;
queue.add(u2);
}
}
}
}
while (d >= 0) {
if (ans[d] >= 0) {
System.out.println(ans[d]+" " + d);
return ;
}
d--;
}
}
public static void updateAns(Nod u) {
for (int i = 0; i < 3; i++) {
int d = u.v[i];
if (ans[d] < 0 || u.dist < ans[d]) ans[d] = u.dist;
}
}
public static void init(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = -1;
}
}
public static void init(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
vis[i][j] = 0;
}
}
}
}
class Nod {
int[] v;
int dist;
public Nod() {
v = new int[3];
}
}