Source Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ss second
#define ff first
#define pb push_back
#define mp make_pair

const int N=300050;
ll n;
ll a[N],b[N];
ll prea[N]={},preb[N]={};
int main(){
    ios_base::sync_with_stdio(0);
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
        prea[i+1]=prea[i]+a[i];
    }
    for(int i=0;i<n;i++){
        cin>>b[i];
        preb[i+1]=preb[i]+b[i];
    }
    if(prea[n]>preb[n]){
        cout<<-1<<endl;
        return 0;
    }
    ll tmp=0;
    int frst=n+1;
    ll travel=0;
    for(int i=1;i<=n;i++){
        tmp+=(b[i-1]-a[i-1]);
        //cout<<tmp<<endl;
        if(tmp<0){
            frst=min(frst,i);
        }
        if(tmp>=0&&frst!=n+1){
            travel+=2*(i-frst);
            if(i==n)travel-=(i-frst);
            frst=n+1;
        }
    }
    ll ans=prea[n]+travel+n-1;
    //cout<<ans<<' '<<travel<<endl;
    ans=min(ans,prea[n]+n-1+n-1);
    cout<<ans<<endl;
    return 0;
}
Copy
Shooting Balloons IDK
GNU G++17
47 ms
10.1 MB
Wrong Answer