22 骑士斗恶龙
作者: Turbo时间限制: 1S章节: 一维数组
问题描述 :
你的王国里有一条n个头的恶龙,你希望雇佣一些骑士把它杀死(也就是砍掉所有的头)。
村里有m个骑士可以雇佣,一个能力值为 x 的骑士可以砍掉恶龙一个直径不超过 x 的头,且需要报酬 x 个金币。
如何雇佣骑士才能砍掉恶龙所有的头,并且支付最小的金币?
注意,一个骑士只能砍一个头并且仅能被雇佣1次。
输入说明 :
输入包含多组测试数据。
每组测试数据的第一行输入两个整数n和m(m和n都在1到20000 之间), n表示龙拥有的头的数目 , m表示王国中的骑士数。
接下来的 n 个整数为龙头的直径,再接下来m个整数为骑士的能力值。
输出说明 :
对于每组测试数据, 输出一行包含国王杀死龙需要支付的最低数量的金币。如果骑士不可能杀死龙, 输出一行:
“Lose!”(输出不包含引号)
输入范例 :
2 3
5
4
7
8
4
2 1
5
5
10
输出范例 :
11
Lose!
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class test_22 {
/**
* 22 骑士斗恶龙
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, m, a;
while (sc.hasNext()) {
try {
n = sc.nextInt();
m = sc.nextInt();
sc.nextLine();
ArrayList<Integer> dragon = new ArrayList<>(n);
ArrayList<Integer> soldiers = new ArrayList<>(m);
//龙
for (int i = 0; i < n; i++) {
dragon.add(sc.nextInt());
}
//士兵
for (int i = 0; i < m; i++) {
soldiers.add(sc.nextInt());
}
if (m < n) {
System.out.println("Lose!");
} else {
Collections.sort(dragon);
Collections.sort(soldiers);
int i = 0, sum = 0, count = 0;
while (i < soldiers.size() && count < dragon.size()) {
if (soldiers.get(i) < dragon.get(count)) {
while ( soldiers.get(i) < dragon.get(count)) {
i++;
if(i==soldiers.size()){
break;
}
}
}
if(i==soldiers.size()){
break;
}
sum += soldiers.get(i);
count++;//龙向后移
i++;//士兵后移
}
if (count == dragon.size()) {
System.out.println(sum);
} else {
System.out.println("Lose!");
}
}
dragon.clear();
soldiers.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}