CSU-ICPC2019年寒假集训结训测试 J-Boredom

Description

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 ≤ 10^5) that shows how many numbers are in Alex’s sequence.
The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ 10^5)

Output

Print a single integer — the maximum number of points that Alex can earn.

Sample Input
9
1 2 1 3 2 2 2 2 3
Sample Output
10

Hint

Consider the 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.


题面大意

在一串数列当中,每次删除1个大小为ak的元素可以获得分数ak,但大小为ak-1,ak+1的元素也会被删除。求可以取得的最大分数。

思路

这是一道简单dp题,用刷表法解决。
首先,对于值相等的元素,显然我们会全部选取,可声明数组cnt[],cnt[i]意指元素i在数列中出现的次数。
对于动态规划部分,声明数组dp[],dp[i]代表将元素从小到大取,取到该元素时所能获得的最大分数。显然,有两种情况:

  1. 选取值为i-1的元素,则值为i的元素被忽略,dp[i]=dp[i-1];
  2. 选取值为i-2的元素和值为i的元素,忽略值为i-1的元素,dp[i]=dp[i-2]+cnt[i]*i;

又题目要求取分数最大值,故得状态转移方程:dp[i]=max(dp[i-1],dp[i-2]+cnt[i]*i)。

AC代码:
#include
using namespace std;
long long cnt[100000+5];
long long dp[100000+5];
int main()
{
 long long a,n,maxx=-1;
 scanf("%lld",&n);
 while(n--)
 {
  scanf("%lld",&a);
  maxx=max(a,maxx);//缩小dp范围
  cnt[a]++;
 }
 dp[1]=cnt[1];
 for(long long i=2;i<=maxx;i++)
  dp[i]=max(dp[i-1],dp[i-2]+cnt[i]*i);
 printf("%lld",dp[maxx]);
 return 0;
}

你可能感兴趣的:(数据结构与算法)