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
ll n;
ll a[300100],b[300100];
ll dp[300100][2];
bool ok[300100];
ll go(int cr,int g){
    if(cr>=n)return 0;
    ll &ret=dp[cr][g];
    if(ret!=-1)return ret;
    ret=1e9;
    ret=min(ret,(n-1-cr)*2);
    int y=0;
    if(g==1)y=2;
    ret=min(ret,go(cr+1,g)+1+2);
    if(ok[cr]){
        ret=min(ret,go(cr+1,0)+1);
    }
    return ret;

}
int main(){
    cin>>n;
    ll ans=0;
    memset(dp,-1,sizeof dp);
    ll x=0;
    for(int i=0;i<n;i++){cin>>a[i];ans+=a[i];}
    int last=-1;
   //ans+=n-1;
    for(int i=0;i<n;i++){
        cin>>b[i];
        x+=b[i];
        x-=a[i];
        if(x>=0){
            ok[i]=1;
        }

    }
    if(x<0){
        cout<<-1;
        return 0;
    }
    cout<<ans+go(0,0)<<endl;
    return 0;
}
 /*
3 3
///
/.\
\\/

 */
Copy
Shooting Balloons Wesam
GNU G++17
197 ms
24.6 MB
Accepted