田忌賽馬(Tian Ji -- The Horse Racing)中的動態規劃以及貪心算法

這兩天碰到一道看似很簡單,但是實際做起來確實比較難的問題,在這裏分析討論一下。

題目:http://acm.hdu.edu.cn/showproblem.php?pid=1052

Tian Ji -- The Horse Racing

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11410    Accepted Submission(s): 3196

Problem Description
Here is a famous story in Chinese history.

"That was about 2300 years ago. General Tian Ji was a high official in the country Qi. He likes to play horse racing with the king and others."

"Both of Tian and the king have three horses in different classes, namely, regular, plus, and super. The rule is to have three rounds in a match; each of the horses must be used in one round. The winner of a single round takes two hundred silver dollars from the loser."

"Being the most powerful man in the country, the king has so nice horses that in each class his horse is better than Tian's. As a result, each time the king takes six hundred silver dollars from Tian."

"Tian Ji was not happy about that, until he met Sun Bin, one of the most famous generals in Chinese history. Using a little trick due to Sun, Tian Ji brought home two hundred silver dollars and such a grace in the next match."

"It was a rather simple trick. Using his regular class horse race against the super class from the king, they will certainly lose that round. But then his plus beat the king's regular, and his super beat the king's plus. What a simple trick. And how do you think of Tian Ji, the high ranked official in China?"



Were Tian Ji lives in nowadays, he will certainly laugh at himself. Even more, were he sitting in the ACM contest right now, he may discover that the horse racing problem can be simply viewed as finding the maximum matching in a bipartite graph. Draw Tian's horses on one side, and the king's horses on the other. Whenever one of Tian's horses can beat one from the king, we draw an edge between them, meaning we wish to establish this pair. Then, the problem of winning as many rounds as possible is just to find the maximum matching in this graph. If there are ties, the problem becomes more complicated, he needs to assign weights 0, 1, or -1 to all the possible edges, and find a maximum weighted perfect matching...

However, the horse racing problem is a very special case of bipartite matching. The graph is decided by the speed of the horses --- a vertex of higher speed always beat a vertex of lower speed. In this case, the weighted bipartite matching algorithm is a too advanced tool to deal with the problem.

In this problem, you are asked to write a program to solve this special case of matching problem.

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.

Sample Input
3 92 83 71 95 87 74 2 20 20 20 20 2 20 19 22 18 0

Sample Output
200 0 0

Source

Recommend
JGShining

動態規劃

因爲貪心算法很難想,所以從先從dp入手了,首先對田忌還有王的馬都按照從快到慢的順序排列。

定義f[i][j]爲,經過了i場比賽後,田忌從最慢的馬開始從後往前使用了j匹馬的最大收益

一.

f[i-1][j]表示經過了i-1場比賽後,田忌已經使用了j匹慢馬的最大收益。當第i場到來時,爲了得到f[i][j],田忌只能使用前面的第i-j匹快馬,

此時f[i][j]=f[i-1][j]+(田忌使用第i-j匹馬與王的第j匹馬拼後的收益,使用函數score(i-j,j)表示)

二.

f[i-1][j-1]表示經過了i-1場比賽後,田忌使用了j-1匹慢馬的最大收益。當第i場到來時,爲了得到f[i][j],田忌使用了第j匹慢馬與王的第i匹快馬拼,此時f[i][j]=f[i-1][j-1]+(田忌使用第n-j+1匹馬與王的第j匹馬拼的最大收益score(n-j+1,j),其中n表示所有總共的馬數)

所以:

f[i][j]=max(f[i-1][j]+score(i-j,j),f[i-1][j-1]+score(n-j+1,j))


具體程序實現如下:

#include<stdio.h>
#include<algorithm>
using namespace std;

int a[1001],b[1001],f[1001][1001];
/*
 *f[i][j]定義爲打了i場比賽,從tanji尾部取出j匹馬取得的最大收益
 */
int score(int i, int j){
	if(a[i]>b[j])
	  return 1;
	else if(a[i]<b[j])
	  return -1;
	else return 0;
}
//初始化
void init(int n){
	//將f全部設置爲0
	for(int p=0; p<=n; p++)
	  for(int q=0; q<=n; q++)
		f[p][q]=0;
	//設置f[i][0],因爲無論tianji還是王都是從最快的馬按照遞減順序出場
	//所以每次只需比較當前的兩匹馬的大小,並在前一次比較的基礎上設置當前f值
	for(int i=1; i<=n; i++){
		if(a[i]>b[i])
			f[i][0]=f[i-1][0]+1;
		else if(a[i]<b[i])
		  f[i][0]=f[i-1][0]-1;
		else
		  f[i][0]=f[i-1][0];//這裏容易漏掉,相等就使用前一次的最優值
	}
	//設置f[i][i],因爲每一次都是tianji都是用最慢的馬和王最快的馬拼,所以tianji從後往前
	//王從前往後比較
	for(int j=n,g=1; j>=1; j--,g++){
		if(a[j]>b[g])
		  f[g][g]=f[g-1][g-1]+1;
		else if(a[j]<b[g])
		  f[g][g]=f[g-1][g-1]-1;
		else
		  f[g][g]=f[g-1][g-1];
	}
}

int maxnum(int i,int j){
	if(i>j)
	  return i;
	else 
	  return j;
}

bool compare(const int& a, const int& b){
	return a>b;
}

int main(){
	int n,max;
	while(1){
		scanf("%d",&n);
		if(n==0)
		  break;
		for(int i=1; i<=n; i++){
			  scanf("%d",&a[i]);
		}
		for(int x=1; x<=n; x++){
			  scanf("%d",&b[x]);
		}
		sort(a+1,a+n+1,compare);
		sort(b+1,b+n+1,compare);
		init(n);
		//動態規劃遞推關係
		for(int j=2; j<=n; j++){
		  for(int k=1; k<j; k++){
			f[j][k]=maxnum((f[j-1][k-1]+score(n-k+1,j)),(f[j-1][k]+score(j-k,j)));
		  }
		}
		//得到收益最大並記錄
		max = f[n][0];
		for(int g=1; g<=n; g++){
			if(f[n][g]>max)
			  max=f[n][g];
		}
		printf("%d\n",max*200);
	}
}

貪心算法

這個貪心算法確實比較難想,可以參考poj上面的大牛http://poj.org/showmessage?message_id=164719,摘錄如下:

貪心的本質在於:田只在有把握贏的情況下拿出快馬和王拼,否則用最慢的馬比掉王的快馬最大程度削弱王的戰鬥力

*
貪心策略:
1,如果田忌的最快馬快於齊王的最快馬,則兩者比。
(因爲若是田忌的別的馬很可能就贏不了了,所以兩者比)
2,如果田忌的最快馬慢於齊王的最快馬,則用田忌的最慢馬和齊王的最快馬比。
(由於所有的馬都贏不了齊王的最快馬,所以用損失最小的,拿最慢的和他比)
3,若相等,則比較田忌的最慢馬和齊王的最慢馬
3.1,若田忌最慢馬快於齊王最慢馬,兩者比。
(田忌的最慢馬既然能贏一個就贏唄,而且齊王的最慢馬肯定也得有個和他比,所以選最小的比他快得。)
3.2,其他,則拿田忌的最慢馬和齊王的最快馬比。
(反正所有的馬都比田忌的最慢馬快了,所以這匹馬必輸,選貢獻最大的,幹掉齊王的最快馬)

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=1005;

int tj[maxn], qw[maxn];

int main()
{
    int n, i, res, max1, max2, min1, min2, cnt;
    while(~scanf("%d", &n) && n)
    {
        for(i=0; i<n; i++)
            scanf("%d", &tj[i]);
        for(i=0; i<n; i++)
            scanf("%d", &qw[i]);
        sort(tj, tj+n);
        sort(qw, qw+n);

        res=0;
        max1=max2=n-1;
        min1=min2=0;
        cnt=0;
        while((cnt++)<n)
        {
            if(tj[max1]>qw[max2])
            {
                res += 200;
                max1--;
                max2--;
            }
            else if(tj[max1]<qw[max2])
            {
                res -= 200;
                min1++;
                max2--;
            }
            else
            {
                if(tj[min1]>qw[min2])
                {
                    res += 200;
                    min1++;
                    min2++;
                }
                else
                {
                    if(tj[min1]<qw[max2]) res -= 200;
                    min1++;
                    max2--;
                }
            }
        }
        printf("%d\n", res);
    }
    return 0;
}


真心佩服古代的孫臏和田忌能想出這麼犀利的方法!

參考:
http://poj.org/showmessage?message_id=164719
http://hi.baidu.com/find_chees/item/2d505a8dbb5824814514cf1e

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章