This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int MX = 5005;
void chmax(int& a, int b){
if(b > a) a = b;
}
int N, arr[MX], dp[MX][MX];
// Observation #1 : We can easily solve this in O(N^3)
// dp(i, j) is the largest beauty of the wall if the highest row includes [i, j]
// the transition is we add another row [j + 1, k] for every j + 1 <= k <= N
// calculating is easy by two pointer
// Observation #2 : Now we can optimize the first solution so that it becomes O(N^2)
// if we place j at a certain position
// and have two pointers (i, k)
// we will see that the beauty will increase a total of O(N) times
// So we can find the positions where the value changes in O(N) for each j
// update those positions
// and after we update max the current value with the previous value
// Note : To make finding range query faster use prefix sum (because l = 0)
struct prefix{
int v[MX];
void build(int p){
for(int i = 0; i <= p; i++) v[i] = i == 0 ? dp[i][p] : max(dp[i][p], v[i - 1]);
}
} ps;
int main(){
ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);
cin >> N;
for(int i = 0; i < N; i++) cin >> arr[i];
for(int p = 0; p < N; p++){
int i = p, k = p + 1, cnt = -1, bot = 0, top = 0;
ps.build(p);
while(i >= 0 && k < N){
if(bot == top){
cnt++; chmax(dp[p + 1][k], ps.v[i] + cnt);
bot += arr[i--]; top += arr[k++];
}else if(bot < top){
bot += arr[i--];
}else if(top < bot){
top += arr[k++];
}
}
for(int j = p + 1; j < N; j++) chmax(dp[p + 1][j], dp[p + 1][j - 1]);
}
int ans = 0;
for(int p = 0; p < N; p++) chmax(ans, dp[p][N - 1]);
cout << ans << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |