题目描述
“田忌赛马”是中国历史上一个著名的故事。
大约2300年前,齐国大将田忌喜欢和国王赛马,并且约定:每赢一场,对方就要付200元。
假设已知田忌和国王的各自马匹的速度都不相同,请计算田忌最好的结果是什么。
输入
输入包含多组测试样例。
每组样例的第一行是一个整数n(n <= 1000),表示田忌和国王各自参赛的马匹数量。
接下来一行的n个整数表示田忌的马的速度,再接下来一行的n个整数表示国王的马的速度。
n为0时,表示输入数据的结束。
输出
每组数据输出一行,表示田忌最多能够赢得的金额。
样例输入 Copy
3 92 83 71 95 87 74 2 20 19 22 18 0
样例输出 Copy
200 0
#include<iostream>
#include<algorithm>
using namespace std;
struct Tian {
int speed;
bool used = 0;
}t[1024];
struct King {
int speed;
bool used = 0;
}k[1024];
bool cmp1(Tian t1, Tian t2) {
return t1.speed > t2.speed;
}
bool cmp2(King k1,King k2) {
return k1.speed > k2.speed;
}
int main()
{
int horse_number;
while (cin >> horse_number) {
//判断算法结束
if (horse_number == 0)
break;
//读取田的马
for (int i = 0; i < horse_number; i++) {
cin >> t[i].speed;
}
//读取王的马
for (int i = 0; i < horse_number; i++) {
cin >> k[i].speed;
}
//对田忌和国王的马进行排序
sort(t, t + horse_number, cmp1);
sort(k, k + horse_number, cmp2);
int King_Fast_index = 0;
int Tian_Fast_index = 0;
int Tian_Slow_index = horse_number - 1;
int money = 0;
for (int i = horse_number - 1; i >= 0; i--) {
if (k[King_Fast_index].speed > t[Tian_Fast_index].speed) {
//使当前的国王最快与田忌最慢赛跑
k[King_Fast_index].used = 1;
t[Tian_Slow_index].used = 1;
//更新最快和最慢
King_Fast_index++;
Tian_Slow_index--;
money -= 200;
}
else if (k[King_Fast_index].speed < t[Tian_Fast_index].speed) {
//当前田的最快可以干过国王的最快,所以赢一把
k[King_Fast_index].used = 1;
t[Tian_Fast_index].used = 1;
//更新最快和最慢
King_Fast_index++;
Tian_Fast_index++;
money += 200;
}
else {
//当前田的最快可以干过国王的最快,所以赢一把
k[King_Fast_index].used = 1;
t[Tian_Fast_index].used = 1;
//更新最快和最慢
King_Fast_index++;
Tian_Fast_index++;
money += 0;
}
}
cout << money << endl;
}
}