hdoj 1052-Tian Ji -- The Horse Racing

本文详细解析了HDOJ1052题目的贪心算法实现思路,通过比较不同马匹的能力来决定比赛策略,确保田忌能够最大化获胜机会。文章通过具体代码展示了如何通过排序和条件判断来实现这一策略。
/*
hdoj 1052-Tian Ji -- The Horse Racing
written by lky

32    lky      46MS    0K    931B    C++    2008-03-20 21:36:28
 
    //贪心思想:if( 田忌比输了 )-----每次都拿最差的马和王比-----输的彻底。
    //          else if( 田忌比赢了 )-----就直接比掉。
    //          else if( 田忌和王打平)----不能急着比掉(从后往前找)
    //                {
    //                    if( 田忌最差的马和王最差的马比赢了 )----继续找
    //                    else 拿这匹马和与王原先比平的马比----找到了,比平问题解决,再从前往后开始比
    //                }
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 1001;
bool comp(int &a, int &b)
{
    return a > b;
}
int main()
{
    int t[MAX], k[MAX];
    int n, total, i, j, s;
    while (scanf("%d", &n) != EOF && n)
    {
        for (i=0; i<n; ++i)
        {
            scanf("%d", &t[i]);
        }
        for (i=0; i<n; ++i)
        {
            scanf("%d", &k[i]);
        }
        sort(t, t+n, comp);
        sort(k, k+n, comp);
        total = 0;
        int head = 0;
        int tail = n-1;
        int tail2 = n-1;
        for (i=0; i<n; ++i)
        {
            if(t[head] > k[i])
                total += 200, ++head;
            else if(t[head] < k[i])
                total -= 200, --tail;
            else
            {
                for (j=tail, s=tail2; j>=head; --j, --s)
                {
                    if(t[j] > k[s])
                        total += 200;
                    else
                    {
                        if(t[j] < k[i])
                            total -= 200;
                        tail = --j;
                        tail2 = s;
                        break;
                    }
                }
            }
            if(head > tail)
                break;
        }
        cout << total << endl;
    }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值