D - Bonus EXP Editorial by en_translator
This problem can be solved with dynamic programming (DP).
Let \(dp_{even}[k]\) be the maximum total experience point when defeating an even number of monsters out of the first \(k\) monsters to encountered, and \(dp_{odd}[k]\) be that for an odd number of monsters (or \(-\infty\) if it is impossible).
Initially, \(dp_{even}[0]=0\) and \(dp_{odd}[0]=-\infty\).
Here, for \(1\leq i\leq N\), note that the experience point that can be gained from the \(i\)-th monster is solely dependent on
- whether Takahashi chose to defeat it or let it go; and
- (if he decided to defeat it) whether the number of monsters defeated so far is even or odd.
Also, to encounter the first \(i\) monsters and defeat an even number of monsters, the following two cases are only possible:
- defeat an even number of monsters among the first \((k-1)\), and let the \(k\)-th go; or
- defeat an odd number of monsters among the first \((k-1)\), and defeat the \(k\)-th.
Therefore, if we know \(dp_{even}[i-1]\) and \(dp_{odd}[i-1]\), we can find \(dp_{even}[i]\) as
\[ dp_{even}[i]=\max(dp_{even}[i-1],dp_{odd}[i-1]+2A_i). \]
Likewise, \(dp_{odd}[i]\) can be found as
\[ dp_{odd}[i]=\max(dp_{odd}[i-1],dp_{even}[i-1]+A_i). \]
The final answer is \(\max(dp_{even}[N],dp_{odd}[N])\).
The complexity here is \(O(N)\), which is fast enough under the constraints of this problem.
Therefore, the problem has been solved.
Sample code in C++:
#include <bits/stdc++.h>
using namespace std;
#define INF (long long)1e+18
int main(void){
int n;
long long x,dp0=0,dp1=-INF,tmp;
cin>>n;
for(int i=0;i<n;i++){
cin>>x;
tmp=dp0;
dp0=max(dp1+2*x,dp0);
dp1=max(tmp+x,dp1);
}
cout<<max(dp0,dp1)<<endl;
return 0;
}
posted:
last update: