- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 69 lines of C++ from the credited upstream file ccc19s4.cpp.
- The implementation visibly relies on work queue, cached states.
- 9 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4 5#include <bits/stdc++.h>6 7using namespace std;8 9using ll = long long;10 11ll arr[1000015], dp[1000015], st[1000015][20];12 1314ll rmq(ll l, ll r) {15 if (l > r) return 0;16 ll length = r - l + 1, k = 31 - __builtin_clz(length);17 return max(st[l][k], st[r-(1<<k)+1][k]);18}19 20int main() {21 ios_base::sync_with_stdio(false); cin.tie(0);22 23 ll n, k; cin >> n >> k;24 25 for (ll i=1; i<=n; i++) {cin >> arr[i]; st[i][0] = arr[i];}26 27 if (k == 1) {28 cout << accumulate(arr, arr + n + 1, 0LL) << endl;29 return 0;30 }31 32 for (int m = 1; m < 20; m++) {33 for (int i = 1; i + (1<<m)-1 <= n; i++) {34 st[i][m] = max(st[i][m-1], st[i+(1<<(m-1))][m-1]);35 }36 }37 38 deque<ll> red; red.push_back(0);39 deque<ll> blue; blue.push_back(0);40 41 int blockStart = 1;42 for (int i=1; i<=n; i++) {43 if (i % k == 1 && i != 1) { 44 blockStart = i;45 red.clear(); blue.clear();46 47 for (int j=i-k; j<i; j++) { 48 while (!red.empty() && dp[red.back()] <= dp[j]) red.pop_back();49 red.push_back(j);50 51 while (!blue.empty() && dp[blue.back()] + rmq(blue.back()+1, i-1) <= dp[j] + rmq(j+1, i-1)) blue.pop_back();52 blue.push_back(j);53 }54 55 56 }57 58 ll withRed = dp[red.front()] + rmq(blockStart, i);59 ll withBlue = dp[blue.front()] + rmq(blue.front()+1, i);60 dp[i] = max(withRed, withBlue);61 62 63 while (!red.empty() && red.front() <= i-k) red.pop_front();64 while (!blue.empty() && blue.front() <= i-k) blue.pop_front();65 }66 67 68 cout << dp[n] << endl;69}