浙大OJ 1005 Jugs 思维题
🍑 OJ专栏
🍑 ZOJ 1005 Jugs
输入
3 5 4
5 7 3
输出
fill B
pour B A
empty A
pour B A
fill B
pour B A
success
fill A
pour A B
fill A
pour A B
empty B
pour A B
success
🍑 案例1 模拟
🍤 题目条件 Cb >= Ca && Cb >= N
🍤 目标 B罐装 N 单位的水
🥞 A空 B空 --> 满上B
🥞 A空 B不空 --> B倒A
🥞 A不空 B不空 --> 清空A
🍁 反复直到 B 为 N
👨🏫 结果不唯一,不要求最优解
🍑 满B --> A (清 A)
import java.util.Scanner;
public class Main
{
static int p;
static boolean check(int x)
{
if (x == p)
{
System.out.println("success");
return true;
}
return false;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int a, b;
int ca, cb;
while (scanner.hasNext())
{
a = scanner.nextInt();
b = scanner.nextInt();
p = scanner.nextInt();
// c1 c2 表示a b 的现有水量
ca = 0;
cb = 0;
while (true)
{
// 只要b空就装满
if (cb == 0)
{
cb = b;
System.out.println("fill B");
if (check(cb))
break;
int t = ca;
ca = Math.min(ca + cb, a);// 顶多加满
cb = Math.max(0, cb - (ca - t));
System.out.println("pour B A");
if (check(cb))
break;
}
while (cb != 0)
{
// 先清空 a
ca = 0;
System.out.println("empty A");
// 再倒
ca = Math.min(ca + cb, a);// 顶多加满
cb = Math.max(0, cb - ca);
System.out.println("pour B A");
if(cb==p)//这里不能check,不然就重复输出啦,WA!!!
break;
}
if (check(cb))
break;
}
}
}
}
🍑 满A --> B (清B)
👨🏫 参照题解
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int a, b, p;
int ca, cb;
while (sc.hasNextInt())
{
a = sc.nextInt();
b = sc.nextInt();
p = sc.nextInt();
ca = 0;
cb = 0;
while (true)
{
// 只要 a 空,就满上
if (ca == 0)
{
ca = a;
System.out.println("fill A");
}
// A --> B
int t = cb;
cb = Math.min(b, cb + ca);// 加满 B
ca = Math.max(0, ca - (cb - t));// t 是 cb 原值,当前值-原值 == 变化值
System.out.println("pour A B");
if (cb == p)// 收工
{
System.out.println("success");
break;
}
// 只要 b 满就清空,因为经过上一个if判断说明 cb 不等于 p,当 cb = b时,A --> B 不可能使得 cb 变成 P
if (cb == b)
{
cb = 0;
System.out.println("empty B");
}
}
}
sc.close();
}
}