Codeforces Round #260 (Div. 1) 455 A. Boredom (DP)

来源:互联网 发布:win7仿苹果mac os x 编辑:程序博客网 时间:2024/05/24 06:39
A. 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 a1a2, ..., an (1 ≤ ai ≤ 105).

Output

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

Sample test(s)
input
21 2
output
2
input
31 2 3
output
4
input
91 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.


题目大意:每次可以取一个数k可以获得k积分,同时去掉所有的k-1,和k+1,问数被取完后的最大积分;

真的,做dp一类的题,知道了怎么构造状态方程,就是很水的题目了,问题就在自己能不能把想到的思路转换成方程

还是看了网上的代码,写出来的状态方程

思路:

将每个数的个数存放在一个数组a里面,那么消除这个数i得到的积分为:a[i]*i(i个数,可以被消灭i次);

构造状态转移方程:dp[i]=max(dp[i-1],dp[i-2]+a[i]*i);

因为当你取i数的时候两种可能:第一,i-1数被取过了,那么这时候i数在取i-1的时候被消灭了,所以dp[i]=dp[i-1];

第二:i-1没有被取过,说明i-2数被取了然后顺势消灭了i-1数,导致我们现在可以取到i数,所以dp[i]=dp[i-2]+a[i]*i;

AC代码:

#include <iostream>#include <algorithm>#include<cstdio>#include<cstring>using namespace std;char maps[20][20];long long int a[100005];//都要用longlong 不然会爆int;long long int dp[100005];int main(){    int n;    scanf("%d",&n);    int tp,maxx=0;    for(int i=1;i<=n;i++){        scanf("%d",&tp);        a[tp]++;        maxx=max(maxx,tp);    }    dp[0]=0,dp[1]=a[1];    for(int i=2;i<=maxx;i++){        dp[i]=max(dp[i-2]+a[i]*i,dp[i-1]);    }    printf("%lld\n",dp[maxx]);    return 0;}


原创粉丝点击