(CodeForces - 455A)Boredom
time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output
Alex doesn’t like boredom. That’s why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let’s denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
Input
The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex’s sequence.
The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ 105).
Output
Print a single integer — the maximum number of points that Alex can earn.
Examples
input
2
1 2
output
2
input
3
1 2 3
output
4
input
9
1 2 1 3 2 2 2 2 3
output
10
Note
Consider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.
题目大意:一个有n个数的数字串,当你将这个数字串中的ak这个数删除时,这个数字串中所有的ak-1和ak+1都将会被删除(注意这不是数组下标,即不是这个数的相邻两个数,因为这样wa了几发),相应的你会得到ak分数,问当你把所有数字都删除的时候所能获得的最大分数是多少。
思路:可从dp角度考虑。设f[i]表示i这个数字删或者不删时所能得到分数的最大值。当i这个数字不删时,那么必定i-1会删除,此时f[i]=f[i-1];当i这个数字删除时,则f[i]=f[i-2]+i*num[i](num[i]记录数字i出现的个数)。
综上所述,f[i]=max(f[i-1],f[i-2]+i*num[i])。
(其中初值为f[0]=0,f[1]=num[1])
显然答案是,f[mx] (mx表示数字串中最大的那个数)。
ps:最大的情况是105∗105会爆int,所以要开long long
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn=100005;
LL f[maxn],num[maxn];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int x,mx=0;
memset(num,0,sizeof(num));
for(int i=0;i<n;i++)
{
scanf("%d",&x);
if(mx<x) mx=x;
num[x]++;
}
f[0]=0;
f[1]=num[1];
for(int i=2;i<=mx;i++)
f[i]=max(f[i-1],f[i-2]+i*num[i]);
printf("%lld\n",f[mx]);
}
return 0;
}
在CodeForces的455A题中,Alex必须从序列中删除元素以获取最高分数。每次删除数字ak,他得到ak分,并移除ak+1和ak-1。目标是最大化得分。给定一个数字序列,输出最大可能得分。通过动态规划解决,以f[i]表示考虑数字i时的最大分数,f[i]=max(f[i-1], f[i-2]+i*num[i]),其中num[i]是数字i的出现次数,最终答案是f[mx],mx为序列中的最大数。"
106333974,7475565,Android Studio代码重构实战指南,"['Android开发', 'IDE工具', '代码质量', '重构技巧']
318

被折叠的 条评论
为什么被折叠?



