Source Code
#include <bits/stdc++.h>
#define int long long
#define all(a) a.begin(),a.end()
#define pii pair<int,int>
#define F first
#define S second
#define mp make_pair
#define md ((int)1e9+7)
using namespace std;
signed main(){
	int n ;
	cin>>n ;
	vector<int> a(n);
	int ball = 0 , bul = 0 ;
	for(int&x:a) cin>>x , ball+=x ;
	vector<int> b(n);
	for(int&x:b)cin>>x,bul+=x ;
	if(bul<ball){
		cout << -1  ;
		return 0 ;
	}
	int sum = 0 ;
	set<int> in ;
	int sec=n-1+ball;
	int ans = 1e18 ;
	for(int i=0;i<n;i++){
	//	cout << endl ;
		sum-=a[i] ;
		sum+=b[i] ;
//		cout << i << " " ;
		if(sum>=0){
			if(in.empty()){}
//	cout << "back to " << *in.begin()  ;
			else{sec+=(i-*in.begin())*(i==n-1?1:2);
			in.clear() ;}
		}
		else{
			in.insert(i) ;
		}
		if(i!=n-1&&sum>=0)ans=min(ans,sec+(n-1-(i+1))) ;
		else if(i==n-1) ans=min(ans,sec) ;
	}
	cout << min(ans,ball+2*(n-1)) ; 
	return 0 ;
}
Copy
Shooting Balloons Boredom
GNU G++17
221 ms
19.3 MB
Accepted