HDOJ田忌赛马--贪心算法

Input

The input consists of up to 50 test cases. Each case starts with a positive integer n (n <= 1000) on the first line, which is the number of horses on each side. The next n integers on the second line are the speeds of Tian’s horses. Then the next n integers on the third line are the speeds of the king’s horses. The input ends with a line that has a single 0 after the last test case.

Output

For each input case, output a line containing a single number, which is the maximum money Tian Ji will get, in silver dollars.

贪心算法

这个贪心算法确实比较难想,可以参考poj上面的大牛http://poj.org/showmessage?message_id=164719,摘录如下:

贪心的本质在于:田只在有把握赢的情况下拿出快马和王拼,否则用最慢的马比掉王的快马最大程度削弱王的战斗力

*
贪心策略:
1,如果田忌的最快马快于齐王的最快马,则两者比。
(因为若是田忌的别的马很可能就赢不了了,所以两者比)
2,如果田忌的最快马慢于齐王的最快马,则用田忌的最慢马和齐王的最快马比。
(由于所有的马都赢不了齐王的最快马,所以用损失最小的,拿最慢的和他比)
3,若相等,则比较田忌的最慢马和齐王的最慢马
3.1,若田忌最慢马快于齐王最慢马,两者比。
(田忌的最慢马既然能赢一个就赢呗,而且齐王的最慢马肯定也得有个和他比,所以选最小的比他快得。)
3.2,其他,则拿田忌的最慢马和齐王的最快马比。
(反正所有的马都比田忌的最慢马快了,所以这匹马必输,选贡献最大的,干掉齐王的最快马)

#include <iostream> #include<algorithm> #include<string.h> #include<stdio.h> using namespace std; int main() {     int n;     while(cin>>n&&n!=0)     {         int tj[1001],king[1001],count=0;         int tj_min=0,tj_max=n-1;         int king_min=0,king_max=n-1;         for(int i=0; i<n; i++)             cin>>tj[i];         for(int i=0; i<n; i++)             cin>>king[i];         sort(tj,tj+n);         sort(king,king+n);         while(n--)         {             if(tj[tj_max]>king[king_max])             {                 count++;                 tj_max--;                 king_max--;             }             else if(tj[tj_max]<king[king_max])             {                 count--;                 tj_min++;                 king_max--;             }             else             {                 if(tj[tj_min]>king[king_min])                 {                     count++;                     tj_min++;                     king_min++;                 }                 else                 {                     if(tj[tj_min]<king[king_max])                     count--;                     tj_min++;                     king_max--;                 }             }

        }          cout<<count*200<<endl;

    }           return 0;

}

哈哈,田忌赛马思路懂了大笑
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值