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;
#define ll long long int
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
const ll N=5005;
const ll mod=1e9+7;
void solve()
{
int n;
cin>>n;
vector<int>a(n),prf(n+1);
for(int i=0;i<n;i++)
{
cin>>a[i];
prf[i+1]=a[i]+prf[i];
}
vector<pair<int,int>>dp(n+1,{-1e9,0});
dp[0]={0,0};
pair<int,int> tmp={0,0};
for(int i=0;i<n;i++)
{
if(dp[i]==(pair<int,int>){-1e9,0}){
dp[i]={tmp.first,tmp.second+(a[i])};
tmp.second+=a[i];
}
else{
tmp=dp[i];
}
ll l = i+1, r = n, ans = n+1;
//binary search for finding the shortest ending index
while(l <= r)
{
int mid = (l + r) >> 1;
int loss=0;
loss=dp[i].second;
if(prf[mid] - prf[i] >= dp[i].second)
{
ans = mid; r = mid - 1;
}else{
l = mid + 1;
}
}
if(ans==n+1)continue;
pair<ll,ll> opt1=dp[ans];
pair<ll,ll> opt2={dp[i].first+1,prf[ans] - prf[i]};
dp[ans].first=max(opt1.first,opt2.first);
// if opt1.first==opt2.first then min value segment is preferable
if(dp[ans].first==opt2.first)
{
dp[ans].second=opt2.second;
}
else
{
dp[ans].second=opt1.second;
}
}
int ans=0;
for(int i=0;i<=n;i++){
ans=max(ans,dp[i].first);
}
cout<<ans<<endl;
}
int main() {
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
IOS;
ll T;
T=1;
// cin >> T;
while(T--){
solve();
}
return 0;
}
Compilation message (stderr)
segments.cpp: In function 'void solve()':
segments.cpp:40:17: warning: variable 'loss' set but not used [-Wunused-but-set-variable]
40 | int loss=0;
| ^~~~
# | 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... |