您的位置:首页 > 其它

田忌赛马(tian ji racing)

2016-04-15 16:52 260 查看
[align=left]描述[/align]
田忌与齐王赛马,双方各有n匹马参赛(n<=100),每场比赛赌注为1两黄金,现已知齐王与田忌的每匹马的速度,并且齐王肯定是按马的速度从快到慢出场,现要你写一个程序帮助田忌计算他最好的结果是赢多少两黄金(输用负数表示)。

Tian Ji and the king play horse racing, both sides have n horse (n is no more the 100), every game a bet of 1 gold, now known king and Tian Ji each horse's speed, and the king is definitely on the horse speed from fast to slow, we want you to write a program
to help Tian Ji his best result is win the number gold (lost express with the negative number).

[align=left]输入[/align]
多个测例。

每个测例三行:第一行一个整数n,表示双方各有n匹马;第二行n个整数分别表示田忌的n匹马的速度;第三行n个整数分别表示齐王的n匹马的速度。

n=0表示输入结束。

A plurality of test cases.

Each test case of three lines: the first line contains an integer n, said the two sides each have n horse; second lines of N integers n Tian Ji horse speed; third lines of N integers King n horse speed.

N = 0 indicates the end of input.

[align=left]输出[/align]
每行一个整数,田忌最多能赢多少两黄金。

how many gold the tian ji win

[align=left]输入样例[/align]
3

92 83 71

95 87 74

2

20 20

20 20

2

20 19

22 18

3

20 20 10

20 20 10

0

[align=left]输出样例[/align]
1

0

0

0

动态规划:

f[i][j]表示第i场比赛,从“尾”取了j匹较弱的马,从“头”取了i-j匹较强的马,所能够得到的最大盈利

可以得到f[i][j]的两种状态

f[i-1][j]:第i-1场比赛,从“尾”取匹j匹叫弱的马,那么转移到f[i][j],将第i-j匹马派出pk;
f[i-1][j-1]:第i-1场比赛,从“尾”取匹j-1匹叫弱的马,那么转移到f[i][j],将第j匹马派出pk;

那么可以得到状态转移方程:
f[i][j] = max((f[i-1][j-1]+pk(n-j+1,i)) , (f[i-1][j]+pk(i-j,i)));

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

int a[1010];                //田忌马的速度
int b[1010];                //齐王马的速度
int f[1010][1010];          //f[i][j]表示第i场比赛,从“尾”取了j匹较强的马,从“头”取了i-j匹较弱的马,所能够得到的最大盈利
bool cmp(int a, int b)
{
return a > b;
}

//田忌的第i匹马和齐王的第j匹马pk
int pk(int i, int j)
{
if(a[i] > b[j])
return 1;
else if(a[i] < b[j])
return -1;
else
return 0;
}
int main()
{
int n;
while(cin >> n && n)
{
for(int i = 1; i <= n; i ++)
cin >> a[i];
for(int i = 1; i <= n; i ++)
cin >> b[i];

//从大到小排序
sort(a+1, a+n+1, cmp);
sort(b+1, b+n+1, cmp);

for(int i = 1; i <= n; i ++)
{
//j = 0:第i局比赛,只使用前(i-0)匹马
f[i][0] = f[i-1][0]+pk(i, i);
//j = i:第i局比赛,只用后i匹马
f[i][i] = f[i-1][i-1]+pk(n-i+1, n-i+1);
}

for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
f[i][j] = max((f[i-1][j-1]+pk(n-j+1,i)) , (f[i-1][j]+pk(i-j,i)));
}
}

int ans = f
[0];
for(int j = 1; j <= n; j++)
{
ans = max(ans, f
[j]);
}
cout << ans << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: