题目描述:
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你能得到最大分值。
Examples:
Input1:
2
1 2
Output1:
2
Input2:
3
1 2 3
Output2:
4
Input3:
9
1 2 1 3 2 2 2 2 3
Output3:
10
个人思路:
- set去重处理,并且记录每个数出现的次数。
- 利用set的升序排列。
- 初始化score[1] = a[1];
- 那么对于set中的数字
如果a[i-1] != a[i] - 1,那么score[i] = score[i-1] + a[i]*a[i]的个数
否则,score[i] = max(score[i-1], score[i-2] + a[i]*的个数) - 那么显然,最后的答案就在score[set.size()]中。
代码块:
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
using namespace std;
int n;
long long a[500005];
long long f[500005];
int num[500005];
map<int, int>mp;
set<int>st;
void solve(){
int tot = 0;
for(int i = 0; i <= n; ++i) num[i] = 1;
sort(a+1, a+n+1);
f[1] = a[1];
a[0] = 0;
f[0] = 0;
for(int i = 1; i <= n; ++i){
if(a[i] == a[i-1]){
num[tot]++;
continue;
}
mp[a[i]] = ++tot;
}
int cnt = 0;
for(auto &i : st) a[++cnt] = i;
for(int i = 1; i <= cnt; ++i){
if(a[i-1] == a[i] - 1)
f[i] = max(f[i-1], f[i-2] + a[i] * num[mp[a[i]]]);
else f[i] = f[i-1] + a[i] * num[mp[a[i]]];
}
}
int main(){
cin >> n;
for(int i = 1; i <= n; ++i) {cin >> a[i]; st.insert(a[i]);};
solve();
for(int i = 1; i <= mp.size(); ++i) f[0] = max(f[i], f[0]);
cout << f[st.size()] << endl;
return 0;
}