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>
#define int long long
// #define ll long long
#define pii pair<int, int>
#define all(v) v.begin(), v.end()
using namespace std;
const int oo = 1e18 + 9;
const int MAX = 1e5 + 5, LOGMAX = 20, B = 800, MOD = 1e9 + 7;
int n;
int arr[MAX];
int dp[MAX][LOGMAX][LOGMAX];
int dp2[MAX];
void solve(){
cin >> n;
for(int i = 1; i <= n; i++) cin >> arr[i];
int lg = log2(n);
for(int i = 0; i < MAX; i++){
for(int j = 0; j < LOGMAX; j++){
for(int k = 0; k < LOGMAX; k++){
dp[i][j][k] = oo;
}
}
}
for(int i = 1; i <= n; i++){
if(arr[i] > lg){
cout << "-1\n";
return;
}
dp[i][0][arr[i]] = 0;
dp[i][0][arr[i] - 1] = 1;
}
for(int i = n; i >= 1; i--){
for(int j = 1; i + (1 << j) - 1 <= n; j++){
for(int k = min(LOGMAX - 1, arr[i]); k >= 0; k--){
dp[i][j][k] = min({dp[i][j - 1][k] + dp[i + (1 << (j - 1))][j - 1][k],
dp[i][j - 1][k + 1] + dp[i + (1 << (j - 1))][j - 1][k + 1] + 1});
// cout << i << ' ' << j << ' ' << k << ": " << dp[i][j][k] << '\n';
}
}
}
for(int i = 1; i <= n; i++){
dp2[i] = oo;
for(int j = 0; i - (1 << j) >= 0; j++){
dp2[i] = min(dp2[i - (1 << j)] + dp[i - (1 << j) + 1][j][0], dp2[i]);
}
}
if(dp2[n] >= oo) dp2[n] = -1;
cout << dp2[n] << '\n';
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
while(t--) solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |