题目链接:Click here
题意:就是众所周知的田忌赛马问题,田忌和国王赛马,田忌赢了,奖励200两黄金,输了,扣200两黄金,问田忌的最大收益。
思路:先拿田忌的最快的马和国王最快的马比价,如果田忌最快的马比国王的要快,那么田忌赢,如果田忌最快的比国外最快的慢,则田忌用最慢的和国王最快的比,田忌输。如果田忌最快的和国王最快的相等,那么就比较两者最慢的,如果田忌最慢的马比国王最慢的马快,田忌赢。否则,就拿田忌最慢的和国王最快的马比较,注意!这里田忌不一定会输哦,要比较一下,如果比国王最快的马慢,那么田忌输,否则就打成平手。
具体的看代码吧:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
int cmp(int x, int y)
{//从大到小排序
return x > y;
}
int main()
{
//freopen("testin.txt", "r", stdin);
int n, high1, high2, low1, low2, ans;
int king[1005], tian[1005];
while(scanf("%d", &n) != EOF)
{
if(n == 0)break;
for(int i = 0; i < n; i++)
scanf("%d", &tian[i]);
for(int i = 0; i < n; i++)
scanf("%d", &king[i]);
sort(tian, tian+n, cmp);
sort(king, king+n, cmp);
high1 = high2 = 0;
low1 = low2 = n - 1;
ans = 0;
while(high1 <= low1)
{
if(tian[high1] > king[high2])
{
ans += 200;
high1++;
high2++;
}
else if(tian[high1] < king[high2])
{
ans -= 200;
low1--;
high2++;
}
else
{
if(tian[low1] > king[low2])
{
ans += 200;
low1--;
low2--;
}
else
{
if(tian[low1] < king[high2]) //注意这里一定要判断下才可以确认是否田忌会输
ans -= 200;
low1--;
high2++;
}
}
}
printf("%d\n", ans);
}
return 0;
}