zoj3905 Cake (dp)

题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3905

题意:有n(n is even)个蛋糕,对于每个蛋糕Alice和Bob都会有个评价值。然后分为n/2次,每次Alice挑两个蛋糕让Bob先选(Bob会拿那个自己认为价值高的那个),剩下的那个留给自己。问怎么选使得Alice选的蛋糕的价值最大(Alice认为的价值)。

Cake

Time Limit: 4 Seconds       Memory Limit: 65536 KB

Alice and Bob like eating cake very much. One day, Alice and Bob went to a bakery and bought many cakes.

Now we know that they have bought n cakes in the bakery. Both of them like delicious cakes, but they evaluate the cakes as different values. So they decided to divide those cakes by following method.

Alice and Bob do n / 2 steps, at each step, Alice choose 2 cakes, and Bob takes the cake that he evaluates it greater, and Alice take the rest cake.

Now Alice want to know the maximum sum of the value that she can get.

Input

The first line is an integer T which is the number of test cases.

For each test case, the first line is an integer n (1<=n<=800). Note that n is always an even integer.

In following n lines, each line contains two integers a[i] and b[i], where a[i] is the value of ith cake that Alice evaluates, and b[i] is the value of ith cake that Bob evaluates. (1<=a[i]b[i]<=1000000)

Note that a[1]a[2]..., a[n] are n distinct integers and b[1]b[2]..., b[n] are n distinct integers.

Output

For each test case, you need to output the maximum sum of the value that Alice can get in a line.

Sample Input
1
6
1 6
7 10
6 11
12 18
15 5
2 14
Sample Output
28
Submit      Status

分析:浩哥的文章讲的很好了。窝的dp还是太菜了啊。。。。

dp[i][j]表示前i个Cake中,有j个属于Alice,显然需要保证 i - j >= j 也就是 2*j <= i状态转移 dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - 1] + p[i].a)首先按b从大到小排序去除后效性,

1、dp[i - 1][j]转态转移到dp[i][j]的时候(第i个Cake给Bob),由于i后面的Cake的b都是小于p[i].b的,所有任何i后面的与i配对Bob都会选择第i个;

2、dp[i - 1][j - 1] + p[i].a转态转移到dp[i][j]的时候(第i个Cake给Alice),由于前面的转态都保证了i - j >= j,则转态dp[i - 1][j - 1]中 (i - 1) - 2 * (j - 1) = i - 2*j + 1 > 0,则dp[i - 1][j - 1]保证了Bob至少有一个没有配对,显然此时选择第i个Cake给Alice与前面给Bob的未配对的Cake是可以的。

代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;
const int maxn = 1008;
struct node
{
	int a,b;
	bool operator < (const node &t)const 
	{
		return b>t.b;
	}
}s[maxn];
int dp[maxn][maxn];
int main()
{
	int ncase,n,i,j;
	scanf("%d",&ncase);
	while(ncase--)
	{
		scanf("%d",&n);
		for(i=1;i<=n;i++)
			scanf("%d%d",&s[i].a,&s[i].b);
		sort(s+1,s+1+n);
		for(i=1;i<=n;i++)
		{
			for(j=1;j*2<=i;j++)
			{
				dp[i][j]=max(dp[i-1][j],dp[i-1][j-1]+s[i].a);
			}
		}
		printf("%d\n",dp[n][n/2]);
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值