BZOJ 4247 挂饰 背包DP

时间:2023-03-09 00:39:52
BZOJ 4247 挂饰 背包DP

4247: 挂饰

Time Limit: 1 Sec

Memory Limit: 256 MB

题目连接

http://www.lydsy.com/JudgeOnline/problem.php?id=4247

Description

JOI君有N个装在手机上的挂饰,编号为1...N。 JOI君可以将其中的一些装在手机上。
JOI君的挂饰有一些与众不同——其中的一些挂饰附有可以挂其他挂件的挂钩。每个挂件要么直接挂在手机上,要么挂在其他挂件的挂钩上。直接挂在手机上的挂件最多有1个。
此外,每个挂件有一个安装时会获得的喜悦值,用一个整数来表示。如果JOI君很讨厌某个挂饰,那么这个挂饰的喜悦值就是一个负数。
JOI君想要最大化所有挂饰的喜悦值之和。注意不必要将所有的挂钩都挂上挂饰,而且一个都不挂也是可以的。

Input

第一行一个整数N,代表挂饰的个数。
接下来N行,第i行(1<=i<=N)有两个空格分隔的整数Ai和Bi,表示挂饰i有Ai个挂钩,安装后会获得Bi的喜悦值。

Output

输出一行一个整数,表示手机上连接的挂饰总和的最大值

Sample Input

5
0 4
2 -2
1 -1
0 1
0 3

Sample Output

5

HINT

将挂饰2直接挂在手机上,然后将挂饰1和挂饰5分别挂在挂饰2的两个挂钩上,可以获得最大喜悦值4-2+3=5。
1<=N<=2000
0<=Ai<=N(1<=i<=N)
-10^6<=Bi<=10^6(1<=i<=N)

题意

题解:

背包问题,dp[i][j]表示在考虑第i个物品的时候,还剩下j个挂钩

注意,要按照挂钩多少排序,如果不排序的话,挂钩有可能会变成负数,然后又被加成正数

代码抄自:http://blog.csdn.net/creationaugust/article/details/48133509

代码:

//qscqesze
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <bitset>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
#include <stack>
typedef long long ll;
using namespace std;
//freopen("D.in","r",stdin);
//freopen("D.out","w",stdout);
#define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
#define maxn 4051
#define mod 10007
#define eps 1e-9
int Num;
//const int inf=0x7fffffff; //нчоч╢С
const int inf=0x3f3f3f3f;
inline ll read()
{
ll x=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
//************************************************************************************** struct node
{
int x,y;
};
bool cmp(node a,node b)
{
return a.x>b.x;
}
node a[maxn];
ll dp[maxn>>][maxn];
int main()
{
int n=read();
for(int i=;i<=n;i++)
dp[][i]=dp[i][n+]=-inf;
for(int i=;i<=n;i++)
a[i].x=read(),a[i].y=read();
sort(a+,a++n,cmp);
ll ans=;
dp[][]=;
for(int i=;i<=n;i++)
{
for(int j=;j<=n;j++)
{
dp[i][j]=max(dp[i-][max(j-a[i].x,)+]+a[i].y,dp[i-][j]);
}
}
for(int i=;i<=n;i++)
ans = max(ans,dp[n][i]);
printf("%d\n",ans);
}