【NOJ1047】【演算法實驗四】田忌賽馬(tian ji racing)

AUV火焰發表於2020-11-26

1047.田忌賽馬(tian ji racing)

時限:1000ms 記憶體限制:10000K 總時限:3000ms
描述
田忌與齊王賽馬,雙方各有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).

輸入
多個測例。
每個測例三行:第一行一個整數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.

輸出
每行一個整數,田忌最多能贏多少兩黃金。
how many gold the tian ji win

輸入樣例
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

輸出樣例
1
0
0
0

#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>

using namespace std;

bool cmp(int a,int b)
{
	return a>b;
}

int max(int a,int b)
{
	return a>b?a:b;
}

int main()
{
	int n,tian[105],qi[105];
	int l[106][106];
	while(cin>>n&&n)
	{
		int i,j;
		for(i=0;i<n;i++) cin>>tian[i];
		for(j=0;j<n;j++) cin>>qi[j];
		sort(tian,tian+n,cmp);
		sort(qi,qi+n,cmp);
		for(i=0;i<=n;i++)
			for(j=0;j<=n;j++)
				l[i][j]=0;
		for(i=1;i<=n;i++)
		{
			for(j=1;j<=n;j++)
			{
				//讓我最差的馬跟你最差的馬比,如果能贏,那我就金子+1;
				if(tian[j-1]>qi[i-1])
				{
					l[j][i]=l[j-1][i-1]+1;
				}
				//如果平局,我先比較一下,是跟你最差的馬比賽好,還是跟你最好的馬比賽好,把這兩種情況能拿到的金子數都算出來,選一個max
				else if(tian[j-1]==qi[i-1])
				{
					l[j][i]=max(l[j-1][i-1],l[j-1][i]-1);
				}
				//如果會輸,與其輸給你最差的馬,不如輸給你最好的馬,金子-1也認了,起碼耗掉你一匹最好的馬;
				else
				{
					l[j][i]=l[j-1][i]-1;
				}
			}
		}
		cout<<l[n][n]<<endl;
	}
	return 0;
}

相關文章