Codeforces 456C Boredom

知识点:线性dp(递推)、贪心

题目

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.

输入

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).

输出

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

样例

输入1

2
1 2

输出1

2

输入2

3
1 2 3

输出2

4

输入3

9
1 2 1 3 2 2 2 2 3

输出3

10

提示

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.

题意

一段整数序列中删去一个数字和所有数值加1或减1的数字,并将该数字作为获得的分数,求最多能获得多少分数。

思路

因为删去一个数字的时候,这个数字就是得到的分数,所以对一个给定的序列,序列的分数和是固定的,因为删去一个数字和所有数值加1或减1的数字时无法得到加1或减1的数字的分数,所以希望删去的加1或减1的数字之和最小。
当删去一个数字后,所有数值加1或减1的数字也被删除,此时再删去同一个数字,将不会删去任何数值加1或减1的数字,损失为零,所以可以贪心,一次删除与这个数字相等的所有数字,并获得这个数字与数字个数的乘积的分数。
有序思考,因为存在某一位置的数字是否删去对前面某一位置无影响的情况,所以可以应用动态规划。设当前状态为从开始删数到删去数字i后获得的分数(包括删去i之前的数的状态,因为上述原因无需考虑删去i之前的数的状态(所以是线性dp,否则是状压dp))(不用考虑数字i不删的状态,因为不删的状态转移没有任何影响,如果不删也能得到分数则需要考虑),状态转移,再删去i+1后不会得到任何分数,dp[i+1]=dp[i];因为删去i的同时会删去i+1,所以再删去i+2后能得到i+2的全部分数,dp[i+2]=dp[i]+(i+2)*count(i+2),其中count(x)为数字x的个数。
至此为最小的状态转移,所以状态转移方程为:
dp[0]=0
dp[1]=1*count(1)(删0得不到任何分数,所以不删0)
dp[i]=max(dp[i-1],dp[i-2]+i*count(i))
因为不会得到负分数,所以最后一个状态即为所求。
(以后的题解尝试将状态转移封装成函数)
实现思路见代码。

代码

//克服WA难,终得AC
#include"bits/stdc++.h"
#define ll long long
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rev(i,a,b) for(ll i=a-1;i>=b;i--)
#define reb(i,a,b) for(ll i=a+1;i<b+1;i++)
#define red(i,a,b) for(ll i=b;i>a;i--)
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const int maxn=1e5+10;

ll n;
//tong[i]:数字i的分数之和
ll tong[maxn];
ll dp[maxn];

int main() {
  scanf("%lld",&n);
  rep(i,0,n) {
    ll t;
    scanf("%lld",&t);
    //数字t的分数之和增加t
    tong[t]+=t;
  }
  dp[0]=tong[0];
  dp[1]=max(tong[0],tong[1]);
  //从2到最大位置dp
  rep(i,2,maxn)
  dp[i]=max(dp[i-1],dp[i-2]+tong[i]);
  printf("%lld\n",dp[maxn-1]);//n位置到最大位置没有得到分数,与dp[n-1]等价
  return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值