ZOJ-3905-Cake【贪心】【dp】

ZOJ-3905-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

题目链接:ZOJ-3905

题目大意:n个蛋糕(n一定为偶数),第i个蛋糕对A的价值为a[i],对B的价值为b[i],A任取两个蛋糕,B总是把这两个蛋糕中对于他来说价值较大的那个拿走,剩下的一个给A,问A可以拿到的最大价值总和是多少?

以下是代码:

#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
struct node
{
    int a,b;    
}v[1000];
bool cmp(node x,node y)
{
    return x.b > y.b;
}
int dp[1000][1000];  //a在前i个蛋糕拿j个所能达到的最大值
int main(){
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        for (int i = 1; i <= n ; i++)
        {
            cin >> v[i].a >> v[i].b;
        }
        sort(v + 1,v + n + 1,cmp);   //将蛋糕按b[i]从大到小排序,这保证了对于第i个蛋糕,任何大于i的蛋糕与它匹配时,B必然选第i个;
        memset(dp,0,sizeof(dp));
        for (int i = 1; i <= n; i++)
        {
            for (int j = 0; j <= i / 2; j++)
            {
                if (j > 0)
                    dp[i][j] = max(dp[i - 1][j],dp[i - 1][j - 1] + v[i].a);   //第i个蛋糕,a取不取
                else
                    dp[i][j] = dp[i - 1][j];
            }
        }
        cout << dp[n][n / 2] << endl;
    }
    return 0;
}

你可能感兴趣的:(ZOJ,3905)