zoj 3956-Course Selection System(揹包)
There are n courses in the course selection system of Marjar University. Thei-th course is described by two values: happiness Hi and creditCi. If a student selects m courses x1, x2, ...,x
Edward, a student in Marjar University, wants to select some courses (also he can select no courses, then his comfort level is 0) to maximize his comfort level. Can you help him?
Input
There are multiple test cases. The first line of input contains an integer T
The first line contains a integer n (1 ≤ n ≤ 500) -- the number of cources.
Each of the next n lines contains two integers Hi andCi (1 ≤ Hi ≤ 10000, 1 ≤Ci ≤ 100).
It is guaranteed that the sum of all n does not exceed 5000.
We kindly remind you that this problem contains large I/O file, so it's recommended to use a faster I/O method. For example, you can use scanf/printf instead of cin/cout in C++.
Output
For each case, you should output one integer denoting the maximum comfort.
Sample Input
2 3 10 1 5 1 2 10 2 1 10 2 10
Sample Output
191 0
Hint
For the first case, Edward should select the first and second courses.
For the second case, Edward should select no courses.
化簡公式發現原公式=(H-C)^2-2*C^2+HC;
即在C固定時,找最大的H便是解。所以揹包求解是正確的。
#include <stdio.h>
#include <string.h>
#include <ctime>
#include <stack>
#include <string>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <map>
#include <ctime>
#include <queue>
#include <vector>
using namespace std;
#define LL long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lowbit(x) (x&-x)
const int maxn = 5e4+7;
const int INF = 0x3f3f3f3f;
int dp[maxn];
int readint()
{
int ret = 0;
char c = getchar();
while (c<'0' || c>'9') c = getchar();
while (c >= '0'&&c <= '9')
{
ret = ret * 10 + c - '0';
c = getchar();
}
return ret;
}
LL f(int h,int c)
{
LL a = (LL)h;
LL b = (LL)c;
return (a-b)*(a-b)-2*b*b+a*b;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int t = 0,n;
n = readint();
memset(dp,-1,sizeof(dp));
dp[0] = 0;
LL ans = 0;
for(int i=0; i<n; i++,t^=1)
{
int a,b;
a = readint();
b = readint();
for(int j=50000; j-b>=0; j--)
{
if(dp[j-b]!=-1)
dp[j] = max(dp[j],dp[j-b]+a);
ans = max(ans,f(dp[j],j));
}
}
printf("%lld\n",ans);
//printf("%I64d\n",ans);
}
return 0;
}