ZOJ - 3956 Course Selection System 公式转化为 0 1背包

题目链接:点击查看

题意:给出n个,hi和ci,随便选出m个来,要求$$(\sum_{i=1}^{m} H_{x_i})^2-(\sum_{i=1}^{m} H_{x_i})\times(\sum_{i=1}^{m} C_{x_i})-(\sum_{i=1}^{m} C_{x_i})^2$$这个最大,

即 sum(H) *(sum(H) - sum(C)) - sum(C) * sum(C)最大,因为c最大为100,一共100个,所以我们就可以吧C的总和作为背包容量,求一个最大的H和了

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 510;
struct node {
	int h, c;
}a[N];
ll dp[50100];
int n;
int main() {
	int T;
	scanf("%d", &T);
	while(T--) {
		scanf("%d", &n);
		for(int i = 1;i <= n; i++) scanf("%d %d", &a[i].h, &a[i].c);
		memset(dp, -1, sizeof(dp));
		dp[0] = 0;
		ll ans = 0;
		for(int i = 1; i <= n; i++) {
			for(int j = 50000; j >= a[i].c; j--) {
				if(dp[j - a[i].c] != -1) {
					dp[j] = max(dp[j], dp[j - a[i].c] + a[i].h);
					ans = max(ans, dp[j] * dp[j] - dp[j] * j - j * j);
				}
			}
		}
		printf("%lld\n", ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/mmk27_word/article/details/89042152