Problem:


Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3



Sample input:
2
3 5 2
4 5


Sample output:
9

Submission status: Accepted

Solution code:
N = int(input())
A_list = list(map(int, input().split()))
B_list = list(map(int, input().split()))

total = 0
for i in range(len(B_list)):
    # print("A:", A_list)
    # print("B:", B_list)
    result = A_list[i] - B_list[i]
    if result > 0:
        total += B_list[i]
        A_list[i] = A_list[i] - B_list[i]
        B_list[i] = 0
        continue

    total += A_list[i]
    B_list[i] = B_list[i] - A_list[i]
    A_list[i] = 0

    result = A_list[i+1] - B_list[i]
    if result > 0:
        total += B_list[i]
        A_list[i+1] = A_list[i+1] - B_list[i]
        B_list[i] = 0
    else:
        total += A_list[i+1]
        A_list[i+1] = 0
        B_list[i] = B_list[i] - A_list[i+1]

# print("A:", A_list)
# print("B:", B_list)

print(total)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
s = 0

for i in range(n):
    if a[i] >= b[i]:
        s += b[i]
    else:
        s += a[i]
        b[i] -= a[i]
        if a[i + 1] >= b[i]:
            s += b[i]
            a[i + 1] -= b[i]
        else:
            s += a[i + 1]
            a[i + 1] = 0
print(s)

Submission status: Accepted

Solution code:
import sys

def solve(N, A, B):
    ans = 0
    for i in range(N):
        if A[i] != 0:
            d = min(A[i], B[i])
            A[i] -= d
            B[i] -= d
            ans += d

        if A[i+1] != 0 and B[i] != 0:
            d = min(A[i+1], B[i])
            A[i+1] -= d
            B[i] -= d
            ans += d
    
    return ans

def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    print(solve(N, A, B))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main38():
    num = int(input())
    dataa = input().split()
    datab = input().split()
    numa = []
    numb = []
    for i in range(num):
        numa.append(int(dataa[i]))
        numb.append(int(datab[i]))
    numa.append(int(dataa[num]))
    result = 0
    for i in range(num):
        if numa[i] >= numb[i]:
            result = result + numb[i]
        else:
            result = result + numa[i]
            numb[i] = numb[i] - numa[i]
            if numa[i+1] >= numb[i]:
                result = result + numb[i]
                numa[i+1] = numa[i+1] - numb[i]
            else:
                result = result + numa[i+1]
                numa[i+1] = 0
    print(result)

if __name__ == "__main__":
    main38()

Submission status: Accepted

Solution code:
n=int(input())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
ans=0
for i in range(n):
    if a[i]>=b[i]:
        ans+=b[i]
    else:
        ans+=a[i]
        if b[i]-a[i]>=a[i+1]:
            ans+=a[i+1]
            a[i+1]=0
        else:
            ans+=b[i]-a[i]
            a[i+1]-=b[i]-a[i]

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]

enemy_count=0
for i in range(len(B)):
    if B[i] > A[i]:#B[i]がA[i]より大きい場合
        enemy_count+=A[i]
        if(A[i+1]>B[i]-A[i]):#さらにA[i+1]がB[i]-A[i]より大きい場合。
            A[i+1]-= B[i]-A[i]
            enemy_count += B[i]-A[i]
        else:#A[i+1]がB[i]-A[i]より小さい場合。
            enemy_count+=A[i+1]
            A[i+1]=0
    else:#B[i]がA[i]以下の場合。
        enemy_count+=B[i]
        A[i]-=B[i]

print(enemy_count)

Submission status: Accepted

Solution code:
def smaller(x, y):
	if x < y:
		return x
	return y

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
sum = 0
for i in range(0, N):
	m = smaller(A[i], B[i])
	sum += m
	A[i] -= m
	B[i] -= m
	m = smaller(A[i+1], B[i])
	sum += m
	A[i+1] -= m
	B[i] -= m
print(sum)

Submission status: Accepted

Solution code:
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
Mod = 1000000007



def main(): #startline-------------------------------------------
    N = int(input())
    A = list(map(int,input().split()))
    B = list(map(int,input().split()))
    ans = 0
    for i in range(N):
        ans += min(A[i],B[i])
        B[i] -= min(A[i],B[i])
        ans += min(A[i+1],B[i])
        A[i+1] -= min(A[i+1],B[i])
    print(ans)
if __name__ == "__main__":
    main() #endline===============================================




def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n < 2 is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))):
        if prime[i] == 1:
            for j in range(2*i,n):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n):
        if prime[i] == 1:
            res.append(i)
    return res

class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py

    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)

Submission status: Accepted

Solution code:
import math
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

m_count = 0
for i in range(N):

    m_count += min(A[i], B[i])
    B[i] -= min(A[i], B[i])
    m_count += min(A[i + 1], B[i])
    A[i + 1] -= min(A[i + 1], B[i])

print(m_count)

Submission status: Accepted

Solution code:
N = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

count = 0

for i in range(0, N):
    left = min(a[i], b[i])
    a[i] -= left
    b[i] -= left
    count += left

    if b[i] > 0:
        right = min(a[i+1], b[i])
        a[i+1] -= right
        b[i] -= right
        count += right

print(count)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))

ans = 0
f1 = min(a[0], b[0])
f = [[f1, min(a[1], b[0]-f1)]]
for i in range(1,n):
    f_tmp = min(a[i]-f[i-1][1], b[i])
    f.append([f_tmp, min(a[i+1], b[i]-f_tmp)])
for f_i in f:
    ans += f_i[0]+f_i[1]
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = 0
for i in range(n):
  if a[i]>=b[i]:
    c+=int(b[i])
  else:
    if (a[i]+a[i+1])>=b[i]:
      c+=int(b[i])
      a[i+1]=a[i]+a[i+1]-b[i]
    else:
      c+=int(a[i]+a[i+1])
      a[i+1]=0
print(c)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

ret = 0
for i, b in enumerate(B):
    k1 = min(A[i], b)
    k2 = min(A[i + 1], b - k1)
    A[i + 1] -= k2
    ret += k1 + k2

print(ret)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 28 19:39:02 2019

@author: avina
"""

n = int(input())
l = list(map(int, input().split()))
b = list(map(int, input().split()))

w = 0
for i in range(n):
    if b[i] > l[i]:
        w+= l[i]
        a = b[i] - l[i]
        if a >= l[i+1]:
            w += l[i+1]
            l[i+1] = 0
        else:
            w+= a
            l[i+1] -=a
    else:
        w+=b[i]
print(w)

Submission status: Accepted

Solution code:
n = int(input())
alist = list(map(int, input().split()))
blist = list(map(int, input().split()))
ans = 0

for i in range(n):
    #  左を全力で倒す
    left = min(alist[i],blist[i])
    ans += left
    alist[i] -= left
    blist[i] -= left

    # 残った戦力で右を倒す
    right = min(alist[i+1],blist[i])
    ans += right
    alist[i+1] -= right
    blist[i] -= right
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
assert len(A) == N + 1
assert len(B) == N

n = 0
for i in range(N):
    k0 = min(A[i], B[i])
    B[i] -= k0
    k1 = min(A[i + 1], B[i])
    A[i + 1] -= k1
    n += k0 + k1

print(n)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
out=0
bb=0
for i in range(n):
  if bb<a[n-i]:
    out+=bb
    a[n-i]=a[n-i]-bb
  else:
    out+=a[n-i]
    a[n-i]=0
    
  if a[n-i]<b[n-i-1]:
    out+=a[n-i]
    bb=b[n-i-1]-a[n-i]
  else:
    out+=b[n-i-1]
    bb=0

if a[0] > bb:
  out+=bb
else:
  out+=a[0]
print(out)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

ans = 0
for i in range(N):
    p = min(A[i], B[i])
    ans += p
    B[i] -= p
    p = min(A[i+1], B[i])
    ans += p
    A[i+1] -= p

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

ans = 0
for i in range(N):
    if B[i] < A[i]:
        ans += B[i]
    elif A[i] <= B[i] <= A[i] + A[i+1]:
        ans += B[i]
        A[i+1] -= B[i] - A[i]
    else:
        ans += A[i] + A[i+1]
        A[i] = 0
        A[i+1] = 0

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
ans = 0
for i in range(N):
  if A[i] <= B[i]:
    ans += A[i]
    B[i] -= A[i]
    A[i] = 0
    ans += min(A[i + 1], B[i])
    A[i + 1] = max(A[i + 1] - B[i], 0)
  else:
    ans += B[i]
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
ans = 0
for i in range(n):
    if a[i] <= b[i]:
        ans += a[i]
        b[i] -= a[i]
        a[i] = 0
        ans += min(a[i + 1], b[i])
        a[i + 1] = max(a[i + 1] - b[i], 0)
    else:
        ans += b[i]
print(ans)

Submission status: Accepted

Solution code:
n=input()
a=map(int,raw_input().split())
b=map(int,raw_input().split())
tot=sum(a)
for i in range(n):
    a[i],b[i]=a[i]-min(a[i],b[i]),b[i]-min(a[i],b[i])
    if b[i]>0:
        a[i+1]-=min(a[i+1],b[i])
print tot-sum(a)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    ans = 0
    for i in range(N):
        tmp = min(A[i], B[i])
        ans += tmp
        A[i] -= tmp
        B[i] -= tmp
        if B[i]:
            tmp2 = min(A[i+1], B[i])
            ans += tmp2
            A[i+1] -= tmp2
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
count=0
C=0
for i in range(N):
    a=A[i]+A[i+1]
    if a>B[i]:
        count=count+B[i]
        C=max(B[i]-A[i],0)
        A[i+1]=A[i+1]-C
    elif a==B[i]:
        count=count+B[i]
        A[i+1]=0
    else:
        count=count+a
        A[i+1]=0
print(count)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
total = 0
for i in range(N):
    if A[i] >= B[i]:
        total += B[i]
    else:
        total += A[i] + min(B[i] - A[i], A[i + 1])
        A[i + 1] = max(A[i + 1] - (B[i] - A[i]), 0)
print(total)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

sum = 0
for i in range(N - 1, -1, -1):
	if A[i + 1] >= B[i]:
		sum += B[i]
		A[i + 1] -= B[i]
		B[i] = 0
	else:
		B[i] -= A[i + 1]
		sum += A[i + 1]
		A[i + 1] = 0
		if A[i] >= B[i]:
			sum += B[i]
			A[i] -= B[i]
			B[i] = 0
		else:
			B[i] -= A[i]
			sum += A[i]
			A[i] = 0

print(sum)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
attack = 0
m = sum(A)
for i in range(N):
    attack = A[i] - B[i]
    if attack < 0:
        A[i+1] = max(0, A[i+1] + attack)
    A[i] = max(0, A[i] - B[i])

print(m-sum(A))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))

res = 0
for i in range(n):
    if a[i]>=b[i]:
        res += b[i]
    else:
        res += a[i]
        b[i]-=a[i]
        if a[i+1] >= b[i]:
            res += b[i]
            a[i+1] -= b[i]
        else:
            res += a[i+1]
            a[i+1] = 0
print(res)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

ans = 0
#全ての勇者に対して，どれだけの敵を倒すか決めていく．
for i in range(n):
    if b[i] <= a[i]:
        ans += b[i]
    else:
        ans += a[i]
        b[i] -= a[i]
        if b[i] <= a[i+1]:
            ans += b[i]
            a[i+1] -= b[i]
        else:
            ans += a[i+1]
            a[i+1] = 0

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
lia = list(map(int,input().split()))
lib = list(map(int,input().split()))

ans = 0

for i in range(n):
    a = min(lia[i],lib[i])
    ans += a
    lib[i] -= a
    b = min(lia[i+1],lib[i])
    ans += b
    lia[i+1] -= b

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
lia = list(map(int,input().split()))
lib = list(map(int,input().split()))

ans = 0

for i in range(n):
    a = min(lia[i],lib[i])
    ans += a
    lib[i] -= a
    b = min(lia[i+1],lib[i])
    ans += b
    lia[i+1] -= b

print(ans)

Submission status: Accepted

Solution code:
def main():

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)

    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # open(0).read() is a convenient method:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    if __name__ != '__main__':
        # for test
        sys.stdin = open('sample.txt')
        
    # ----------------------------------
    # main

    N = int(r())
    A = R()
    B = R()
    ans = 0
    for i, b in enumerate(B):
        if A[i] >= b:
            ans += b
            continue
        else:
            ans += A[i]
            b -= A[i]
            if A[i+1] >= b:
                ans += b
                A[i+1] -= b
            else:
                ans += A[i+1]
                A[i+1] = 0
    print(ans)
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # for
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    # to make binary digits text
    >>> a = 5
    >>> bin_str_a = format(a, '#06b')
    >>> print(bin_str_a)
    0b0101 # first 2 strings (='0b') indicates it is binary
    """

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from sys import stdin


def main():
    _ = int(stdin.readline().rstrip())
    As = [int(x) for x in stdin.readline().rstrip().split()]
    Bs = [int(x) for x in stdin.readline().rstrip().split()]
    result = 0
    for i, b in enumerate(Bs):
        min_ = min(As[i], b)
        result += min_
        As[i] -= min_
        b -= min_

        min_ = min(As[i + 1], b)
        result += min_
        As[i + 1] -= min_
    print(result)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
ans=0
mon1=a[0]
mon2=a[0]+a[1]
for i in range(n):
   if b[i] <= mon1:
      ans+=b[i]
      mon1=a[i+1]
      if i<=n-2:
         mon2=a[i+1]+a[i+2]
   elif mon1<b[i]<=mon2:
      ans+=b[i]
      mon1=a[i+1]-(b[i]-mon1) #ここmon2-b[i]のほうがきれい？
      if i<=n-2:
         mon2=mon1+a[i+2]
   else: 
      ans+=mon2 #ここmon2にしないと動かないぞ
      mon1=0
      if i<=n-2:
         mon2=a[i+2]
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
ans=0
mon1=a[0]
mon2=a[0]+a[1]
for i in range(n):
   if b[i] <= mon1:
      ans+=b[i]
      mon1=a[i+1]
      if i<=n-2:
         mon2=a[i+1]+a[i+2]
   elif mon1<b[i]<=mon2:
      ans+=b[i]
      mon1=mon2-b[i] #ここmon2-b[i]のほうがきれい？
      if i<=n-2:
         mon2=mon1+a[i+2]
   else: 
      ans+=mon2 #ここmon2にしないと動かないぞ
      mon1=0
      if i<=n-2:
         mon2=a[i+2]
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))

ans=0
for i in range(n):
    if a[i]<=b[i]:
        ans+=a[i]
        ans+=min(a[i+1],b[i]-a[i])
        a[i+1]=max(a[i+1]-(b[i]-a[i]),0)
    else:
        ans+=b[i]
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

total = 0
for loc in range(len(B)):
    if A[loc] + A[loc + 1] >= B[loc]:
        total += B[loc]
        A[loc + 1] = min(A[loc + 1], A[loc] + A[loc + 1] - B[loc])
    else:
        total += A[loc] + A[loc + 1]
        A[loc + 1] = 0
print(total)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

brave_num = int(input())
monster_list = [int(i) for i in input().split(" ")]
brave_list = [int(i) for i in input().split(" ")]
ans = 0
for i in range(brave_num):
    if monster_list[i] < brave_list[i]:
        ans += monster_list[i]
        brave_list[i] -= monster_list[i]
        monster_list[i] = 0
        if monster_list[i + 1] < brave_list[i]:
            ans += monster_list[i + 1]
            monster_list[i + 1] = 0
        else:
            ans += brave_list[i]
            monster_list[i + 1] -= brave_list[i]
    else:
        monster_list[i] -= brave_list[i]
        ans += brave_list[i]
print(ans)

Submission status: Accepted

Solution code:
#abc135c

n=int(raw_input())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
res=0
for i in xrange(n):
 x=min(a[i],b[i])
 res+=x
 a[i]-=x
 b[i]-=x
 x=min(a[i+1],b[i])
 res+=x
 a[i+1]-=x
 b[i]-=x
print res

Submission status: Accepted

Solution code:
import sys
import math

N = int(input())
AList = [int(n) for n in input().split()]
BList = [int(n) for n in input().split()]

result = 0

for i in range(N):
    i = int(i)

    m = min(AList[i], BList[i])
    AList[i] -= m
    BList[i] -= m
    result += m
    
    m = min(AList[i+1], BList[i])
    AList[i+1] -= m
    BList[i] -= m
    result += m

print(result)

Submission status: Accepted

Solution code:
import numpy as np

s = input().split()
N=int(s[0])
s = input().split()
a = [int(i) for i in s]
s = input().split()
b=[int(i) for i in s]
c=0
for i in range(N):
    if a[i]-b[i]<0:
        c = c+a[i]+min(a[i+1], b[i]-a[i])
        a[i+1]=a[i+1]+a[i]-b[i]
        if a[i+1]<0:
            a[i+1]=0
    else:
        c=c+b[i]
print(c)

Submission status: Accepted

Solution code:
n = int(input())
lst =[list(map(int,input().split())) for i in range(2)]

ans = 0

for i in range(n):
    if i == 0:
        k1 = min(lst[0][i], lst[1][i])
        k2 = min(lst[0][i+1], lst[1][i] - k1)
        ans += k1 + k2
    else:
        k1 = min(lst[0][i] - k2, lst[1][i])
        k2 = min(lst[0][i+1], lst[1][i] - k1)
        ans += k1 + k2

print(ans)

Submission status: Accepted

Solution code:
def read():
    N = int(input())
    A = list( map(int, input().split(" ")) )
    B = list( map(int, input().split(" ")) )

    return (N, A, B)

def kill(A, B):
    if B < A:
        A = A - B
        B = 0
    else:
        B = B - A
        A = 0
    
    return (A, B)

def main(N, A, B):

    for i in range(N):
        A[i], B[i] = kill(A[i], B[i])
        if 0 < B[i]:
            A[i+1], B[i] = kill(A[i+1], B[i])
    
    return (A, B)

N, A, B = read()
print(sum(A) - sum(main(N, A, B)[0]))

Submission status: Accepted

Solution code:
n = int(input())

a = list(map(int, input().split()))
b = list(map(int, input().split()))

maxCount = 0
for i in range(0, n):
    # i番目の敵をできるだけ倒す
    if a[i] > b[i]:
        maxCount += b[i]
        continue
    else:
        maxCount += a[i]
        b[i] -= a[i]
    # i+1番目の敵をできるだけ倒す
    if a[i+1] > b[i]:
        maxCount += b[i]
        a[i+1] -= b[i]
    else:
        maxCount += a[i+1]
        a[i+1] = 0

print(maxCount)

Submission status: Accepted

Solution code:
a = int(input())
ar = list(map(int,input().split(" ")))
br = list(map(int,input().split(" ")))
count = 0
for i in range(a):
    if ar[i] <= br[i]:
        count += ar[i]
        ar[i] == 0
        br[i] -= ar[i]
        if ar[i+1] <= br[i]:
            count += ar[i+1]
            ar[i+1] = 0
        else:
            ar[i+1] -= br[i]
            count += br[i]
    else:
        ar[i] -= br[i]
        count += br[i]
print(count)