Source Code
#include <bits/stdc++.h>

using namespace std;

#define modulo ll (1e9 + 7)
#define neig(a, u, e, v) for(int v, e = (a).head[u] ; ~e and (v = (a).to[e], 1) ; e = (a).nxt[e])

typedef long long ll;

const int N = 3e5 + 9, M = 1e6 + 9, OO = 0x3f3f3f3f;
const ll llOO = 0x3f3f3f3f3f3f3f3f;

ll ballons[N], bullets[N];


int main() {
    cin.tie(0);
    cin.sync_with_stdio(0);

    ll n;  cin >> n;

    ll sum = 0;
    for(int i = 0;i < n;i++) {
        cin >> ballons[i];
        sum += ballons[i];
    }

    for(int i = 0;i < n;i++) {
        cin >> bullets[i];
        sum -= bullets[i];
    }

    if(sum > 0){
        cout << -1;
        return 0;
    }

    ll rem = 0, smallestIdx = -1, totalBullets = 0, ans = 0;
    for(int i = 0;i < n;i++){
        if(i < n - 1)   ans++;
        totalBullets += bullets[i];

        ll mn = min(totalBullets, ballons[i]);
        totalBullets -= mn;
        ballons[i] -= mn;
        ans += mn;

        if(ballons[i]){
            if(smallestIdx == -1){
                smallestIdx = i;
            }
            rem += ballons[i];
            continue;
        }

        if(rem && totalBullets >= rem){
            ll cost1 = (i - smallestIdx) * (i < n - 1 ? 2 : 1);
            ll cost2 = ((n - 1) - smallestIdx);

            if(cost1 > cost2)   continue;

            ans += cost1;
            ans += rem;
            totalBullets -= rem;
            smallestIdx = -1;
            rem = 0;
        }
    }

    cout << ans;
}
Copy
Shooting Balloons Muhammad
GNU G++17
0 ms
520 KB
Wrong Answer