題面:
給一個序列,裏邊有 n 個數,每一步能拿走一個數,比如拿第 i 個數, Ai = x,得到相應的分數 x,但拿掉這個 Ai 後,x+1 和 x-1 (如果有 Aj = x+1 或 Aj = x-1 存在) 就會變得不可拿(但是有 Aj = x 的話可以繼續拿這個 x)。求最大分數。
輸入第一行包含一個整數 n (1 ≤ n ≤ 105),表示數字裏的元素的個數
第二行包含n個整數a1, a2, …, an (1 ≤ ai ≤ 105)
輸出一個整數:n 即你能得到最大分值
sample input:
2
1 2
sample output:
2
sample input:
3
1 2 3
sample output:
4
sample input:
9
1 2 1 3 2 2 2 2 3
sample output:
10
(先選任何一個值爲2的元素,最後數組內剩下4個2。然後4次選擇2,最終得到10分)
思路:
- 給一個序列,裏面有n個數,每一步可以拿一個數,如果拿了這個數,那麼相鄰的兩個數就會變得無法選擇
- 對於dp轉移方程,由於數據範圍進行了更改,如果不取i這個數,則值爲dp[i-1] ,如果取i這個數,不能取i-1,所以取dp[i-2]+dp[i]*i ,所以轉移方程dp[i] = max(dp[i-1], dp[i-2] +a[i]*i)
- 需要注意一下數據範圍的問題,雖然a的數據範圍在int範圍內,但是由於我們求最大分數,所以最終的結果應該用long long 存儲
#include<iostream>
#include<cmath>
using namespace std;
const int N=1e5+1;
int main()
{
int n;
long long x;
int a[N];
long long dp[N];
long long length=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%lld",&x);
a[x]++;
length=max(length,x);
}
dp[1]=a[1];
for(long long i=2;i<=length;i++)
{
dp[i]=max(dp[i-1],dp[i-2]+a[i]*i);
}
printf("%lld",dp[length]);
return 0;
}