HUSTOJ 基础题组1 问题 H: 田忌赛马

博客围绕“田忌赛马”问题展开,已知田忌和国王各自马匹速度不同,需计算田忌最好的比赛结果。输入包含多组测试样例,给出马匹数量及双方马匹速度,输出为田忌最多能赢得的金额。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

“田忌赛马”是中国历史上一个著名的故事。

大约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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值