C - 拿数问题 II
题目描述
YJQ 上完第10周的程序设计思维与实践后,想到一个绝妙的主意,他对拿数问题做了一点小修改,使得这道题变成了 拿数问题 II。
给一个序列,里边有 n 个数,每一步能拿走一个数,比如拿第 i 个数, Ai = x,得到相应的分数 x,但拿掉这个 Ai 后,x+1 和 x-1 (如果有 Aj = x+1 或 Aj = x-1 存在) 就会变得不可拿(但是有 Aj = x 的话可以继续拿这个 x)。求最大分数。
本题和课上讲的有些许不一样,但是核心是一样,需要你自己思考。
Input
第一行包含一个整数 n (1 ≤ n ≤ 105),表示数字里的元素的个数
第二行包含n个整数a1, a2, …, an (1 ≤ ai ≤ 105)
Output
输出一个整数:n你能得到最大分值。
Output
输出一个整数:n你能得到最大分值。
Example
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
题目思路
首先我们用a数组来记录输入的序列,num数组用来记录每个值的个数,score用来记录最大分数。
用sort对a数组排序,方便找到最大值和最小值。再求分数的时候方程为:score[i]=max(score[i-1],score[i-2]+i*num[i])。最后输出一个最大分数即可。
代码实现
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
#define _for(i,a,b) for(int i = (a);i < (b); i++)
#define _rep(i,a,b) for(int i = (a);i <= (b); i++)
const int MAXN = 1e5 + 100;
int n;
long long a[MAXN],num[MAXN],score[MAXN];
long long ans;
int main(){
ios::sync_with_stdio(false);
cin >> n;
_rep(i,1,n){
cin >> a[i];
num[a[i]]++;
}
ans = 0;
sort(a+1,a+n+1);
_rep(i,a[1],a[n]){
score[i] = max(score[i-1],score[i-2] + i*num[i]);
ans = max(ans,score[i]);
// cout << "ans: " << ans << endl;
}
cout << ans << endl;
}