第十四届华中科技大学程序设计竞赛决赛同步赛 F-Beautiful Land(超大背包)

链接: https://www.nowcoder.com/acm/contest/119/F
来源:牛客网

题目描述

It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
Now HUST got a big land whose capacity is C to plant trees. We have n trees which could be plant in it. Each of the trees makes HUST beautiful which determined by the value of the tree. Also each of the trees have an area cost, it means we need to cost c i area of land to plant.
We know the cost and the value of all the trees. Now HUSTers want to maximize the value of trees which are planted in the land. Can you help them?

输入描述:

There are multiple cases.
The first line is an integer T(T≤10), which is the number of test cases.
For each test case, the first line is two number n(1≤n≤100) and C(1≤C≤108), the number of seeds and the capacity of the land. 
Then next n lines, each line contains two integer ci(1≤ci≤106) and vi(1≤vi≤100), the space cost and the value of the i-th tree.

输出描述:

For each case, output one integer which means the max value of the trees that can be plant in the land.

题解:
因为cost很大但是val很小,所以这里改变一下,dp[i][j]表示前i个物品
获得j的价值所需要的最小花费,若dp[i][j]=INF,表示不存在此种情况。
代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
int cost[maxn],val[maxn];
int dp[maxn][maxn*maxn];
int main()
{
    int T;scanf("%d",&T);
    while(T--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
            scanf("%d%d",&cost[i],&val[i]);
        for(int i=0;i<maxn*maxn;i++)
            dp[0][i]=1e9;
        dp[0][0]=0;
        for(int i=1;i<=n;i++)
        {
            for(int j=0;j<maxn*maxn;j++)
            {
                if(j<val[i])
                    dp[i][j]=dp[i-1][j];
                else
                    dp[i][j]=min(dp[i-1][j],dp[i-1][j-val[i]]+cost[i]);
            }
        }
        int ans=0;
        for(int i=0;i<maxn*maxn;i++)
            if(dp[n][i]<=m)ans=i;
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/albertluf/article/details/80255531