const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const ceil=(a)=>{return Math.ceil(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))};const gcd=(x,y)=>{while(y){[x,y]=[y,x%y]}return x};const sum=(arr)=>{return arr.reduce((a,b)=>a+b);};
const isPrime=(n:number):boolean=>{
  if(n<2)return false;
  const suq=Math.sqrt(n);
  for(let i=2;i<=suq;i++){
    if(n%i==0){
      return false;
    }
  }
  return true;
}
const main=()=>{
  let a=tn()
  while(true){
    a++
    if(isPrime(a)){
      to(a)
      return
    }
  }
}
main()


const isPrime = n => {
  if (n < 2) return false;
  if (n === 2 || n === 3 || n === 5) return true;
  if (n % 2 === 0 || n % 3 === 0 || n % 5 === 0) return false;
  let prime = 7;
  let step = 4;
  const limit = Math.sqrt(n);
  while (prime <= limit) {
    if (n % prime === 0) return false;
    prime += step;
    step = 6 - step;
  }
  return true;
};

const main = (input) => {
  const x = Number(input.trim())
  let result = x
  if (result%2 === 0) result++
  while(true) {
  	if (isPrime(result)) break;
  	result += 2
  }
  console.log(result)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


from sys import stdin

def main():
    readline = stdin.readline
    readline()
    *A, = map(int, readline().split())
    *B, = map(int, readline().split())
    ans = 0
    pre = 0
    for a, b in zip(A, B):
        brave = pre + b
        if brave < a:
            ans += brave
            pre = 0
        elif a < pre:
            ans += a
            pre = b
        else:
            ans += a
            pre = brave - a
    if A[-1] < pre:
        ans += A[-1]
    else:
        ans += pre
    print(ans)
    return

main()


#!/usr/bin/env python3

import sys

sys.setrecursionlimit(10**7)

# Override `input` function because `stdin.readline()` is 10x faster than built-in `input()`
input = sys.stdin.readline

def read_h(typ=int):
    return list(map(typ, input().split()))

def read_v(n, m=1, typ=int):
    return [read_h(typ) if m > 1 else typ(input()) for _ in range(n)]

def main():
    n, = read_h()
    A = read_h()
    B = read_h()

    ans = 0
    rem_cap = 0
    for a, b in zip(A, B):
        cap = rem_cap + b
        if a >= cap:
            ans += cap
            rem_cap = 0
        elif rem_cap >= a:
            ans += a
            rem_cap = b
        else:
            ans += a
            rem_cap = cap - a

        #  print('killed:', ans)
        #  print('remaining:', rem_cap)

    if rem_cap >= A[-1]:
        ans += A[-1]
    else:
        ans += rem_cap

    print(ans)

if __name__ == '__main__':
    main()


from sys import stdin

def main():
    readline = stdin.readline
    readline()
    *A, = map(int, readline().split())
    *B, = map(int, readline().split())
    B.append(0)
    ans = 0
    pre = 0
    for a, b in zip(A, B):
        brave = pre + b
        if brave < a:
            ans += brave
            pre = 0
        elif a < pre:
            ans += a
            pre = b
        else:
            ans += a
            pre = brave - a
    print(ans)
    return

main()


#import math
#import itertools
#import numpy as np
#from collections import deque
# sys.setrecursionlimit(10 ** 6)
#mod = 10 ** 9 + 7
#INF = 10 ** 9
#PI = 3.14159265358979323846

INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))

def do():
    n=INT()
    A=LIST()
    B=LIST()
    ans=0
    ta=A[0]
    for i in range(n):
        tb=B[i]
        ans+=min(ta,tb)
        ta,tb=max(0,ta-tb),max(0,tb-ta)
        ta+=A[i+1]
        ans+=min(ta,tb)
        ta=max(0,ta-tb)
        #print(ans,ta,tb)
    print(ans)

if __name__=='__main__':
    do()


#-*-coding:utf-8-*-
import sys
input=sys.stdin.readline
import numpy as np

def main():
    n = int(input())
    mob=np.array(list(map(int,input().split())),dtype=int)
    bra=np.array(list(map(int,input().split())),dtype=int)
    ans=0

    for i in range(n):
        ans += min(mob[i],bra[i])
        ans += min(mob[i+1],bra[i]-min(mob[i],bra[i]))
    print(ans)

if __name__=="__main__":
    main()


N = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
m = 0
ans = 0
for i in range(N):
    cnt = min(a[i],b[i]+m)
    ans += cnt
    m = b[i]+m-cnt
ans += min(a[N],m)
print(ans)


import java.awt.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.ArrayList;
import java.util.Collections;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.FileInputStream;

public class Main{
    public static void main(String args[] ) throws Exception {
        Reader sc=new Reader();
        int n=sc.nextInt();
        int[] a=new int[n+1];
        int[] b=new int[n];
        for(int i=0;i<=n;i++)a[i]=sc.nextInt();
        for(int i=0;i<n;i++)b[i]=sc.nextInt();

        long count=0;

        for(int i=n-1;i>=0;i--){
            for(int j=1;j>=0;j--){

                int x = a[i + j];
                int y = b[i];

                int m=Math.min(y,x);

                count=count+m;
                b[i]=b[i]-m;
                a[i+j]=a[i+j]-m;
            }
        }
        System.out.println(count);

    }
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }

}


import java.io.*;
import java.util.*;
import java.math.*;
// import java.awt.Point;

public class Main {
    InputStream is;
    PrintWriter out;
    String INPUT = "";

    static int mod = 1_000_000_007;
    // int mod = 998244353;
    // long inf = Long.MAX_VALUE/2;
    int inf = Integer.MAX_VALUE/2;

    void solve(){
        int n = ni();
        long[] a = new long[n+1];
        long[] b = new long[n];
        for(int i = 0; i < n+1; i++){
            a[i] = nl();
        }
        for(int i = 0; i < n; i++){
            b[i] = nl();
        }
        long sum = 0;
        long res = a[0];
        for(int i = 0; i < n; i++){
            if(res>=b[i]){
                sum += b[i];
                res = a[i+1];
                continue;
            }
            else{
                long val = Math.min(res+a[i+1], b[i]);
                sum += val;
                res = res+a[i+1]-val;
                continue;
            }
        }
        out.println(sum);
    }

    void run() throws Exception
    {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        out = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        out.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
    }

    public static void main(String[] args) throws Exception { new Main().run(); }

    private byte[] inbuf = new byte[1024];
    private int lenbuf = 0, ptrbuf = 0;

    private int readByte()
    {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns()
    {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b) && b != ' ')){
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n)
    {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m)
    {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private int[] na(int n)
    {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni()
    {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl()
    {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }

}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.StringJoiner;

class Main {

    static PrintWriter out;
    static InputReader sc;

    public static void main(String[] args) {
        sc = new InputReader(System.in);
        out = new PrintWriter(System.out);
        solve();
        out.flush();
    }

    static void solve() {
        int N = sc.nextInt();
        int[] A = sc.nextIntArray(N + 1);
        int[] B = sc.nextIntArray(N);
        long ans = 0;
        if (A[0] < B[0]) {
            ans += A[0];
            B[0] -= A[0];
        } else {
            ans += B[0];
            B[0] = 0;
        }
        for (int i = 1; i < N; i++) {
            if (A[i] < B[i - 1]) {
                ans += A[i];
                A[i] = 0;
            } else {
                ans += B[i - 1];
                A[i] -= B[i - 1];
            }
            if (A[i] < B[i]) {
                ans += A[i];
                B[i] -= A[i];
            } else {
                ans += B[i];
                B[i] = 0;
            }
        }
        if (A[N] < B[N - 1]) {
            ans += A[N];
        } else {
            ans += B[N - 1];
        }
        out.println(ans);
    }

    static void debug(Object... args) {
        StringJoiner j = new StringJoiner(" ");
        for (Object arg : args) {
            if (arg == null) {
                j.add("null");
            } else if (arg instanceof int[]) {
                j.add(Arrays.toString((int[]) arg));
            } else if (arg instanceof long[]) {
                j.add(Arrays.toString((long[]) arg));
            } else if (arg instanceof double[]) {
                j.add(Arrays.toString((double[]) arg));
            } else if (arg instanceof char[]) {
                j.add(Arrays.toString((char[]) arg));
            } else if (arg instanceof Object[]) {
                j.add(Arrays.toString((Object[]) arg));
            } else {
                j.add(arg.toString());
            }
        }
        System.err.println(j.toString());
    }

    static class InputReader {

        private InputStream in;
        private byte[] buffer = new byte[1024];
        private int curbuf;
        private int lenbuf;

        public InputReader(InputStream in) {
            this.in = in;
            this.curbuf = this.lenbuf = 0;
        }

        public boolean hasNextByte() {
            if (this.curbuf >= this.lenbuf) {
                this.curbuf = 0;
                try {
                    this.lenbuf = this.in.read(this.buffer);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (this.lenbuf <= 0) {
                    return false;
                }
            }
            return true;
        }

        private int readByte() {
            if (this.hasNextByte()) {
                return this.buffer[this.curbuf++];
            } else {
                return -1;
            }
        }

        private boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }

        private void skip() {
            while (this.hasNextByte() && this.isSpaceChar(this.buffer[this.curbuf])) {
                this.curbuf++;
            }
        }

        public boolean hasNext() {
            this.skip();
            return this.hasNextByte();
        }

        public String next() {
            if (!this.hasNext()) {
                throw new NoSuchElementException();
            }
            StringBuilder sb = new StringBuilder();
            int b = this.readByte();
            while (!this.isSpaceChar(b)) {
                sb.appendCodePoint(b);
                b = this.readByte();
            }
            return sb.toString();
        }

        public int nextInt() {
            if (!this.hasNext()) {
                throw new NoSuchElementException();
            }
            int c = this.readByte();
            while (this.isSpaceChar(c)) {
                c = this.readByte();
            }
            boolean minus = false;
            if (c == '-') {
                minus = true;
                c = this.readByte();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res = res * 10 + c - '0';
                c = this.readByte();
            } while (!this.isSpaceChar(c));
            return minus ? -res : res;
        }

        public long nextLong() {
            if (!this.hasNext()) {
                throw new NoSuchElementException();
            }
            int c = this.readByte();
            while (this.isSpaceChar(c)) {
                c = this.readByte();
            }
            boolean minus = false;
            if (c == '-') {
                minus = true;
                c = this.readByte();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res = res * 10 + c - '0';
                c = this.readByte();
            } while (!this.isSpaceChar(c));
            return minus ? -res : res;
        }

        public double nextDouble() {
            return Double.parseDouble(this.next());
        }

        public int[] nextIntArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = this.nextInt();
            }
            return a;
        }

        public long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++) {
                a[i] = this.nextLong();
            }
            return a;
        }

        public char[][] nextCharMap(int n, int m) {
            char[][] map = new char[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = this.next().toCharArray();
            }
            return map;
        }
    }
}


import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws FileNotFoundException {

		//    	File file = new File("src/in.txt");
		//    	Scanner sc = new Scanner(file);

		Scanner sc = new Scanner(System.in);

		int N = sc.nextInt();

		int[] A = new int[N + 1];
		int sum = 0;
		for (int i = 0; i <= N; i++) {
			A[i] = sc.nextInt();
			sum += A[i];
		}
		int[] B = new int[N];
		for (int i = 0; i < N; i++) {
			B[i] = sc.nextInt();
		}
		for(int i=0;i<N;i++) {
			if(B[i]>=A[i]) {
				B[i]-=A[i];
				A[i]=0;
				if(B[i]>=A[i+1]) {
					A[i+1]=0;
				} else {
					A[i+1] -= B[i];
				}
			} else {
				A[i] -=B[i];
			}
		}
		int sum2 = 0;
		for (int i = 0; i <= N; i++) {
			sum2 += A[i];
		}
		System.out.println(sum-sum2);

	}
}


// template for atcoder
import java.util.*;
import java.io.*;
import static java.lang.Math.*;

public class Main {

    private static final int MOD = (int)1e9 + 7; //998244353;
    private static final long INF = (long)1e15;

    public Main(FastScanner in, PrintWriter out) {
        int n = in.nextInt();
        int[] A = new int[n + 1];
        for (int i = 0; i <= n; i++) A[i] = in.nextInt();
        long res = 0;
        int prev = 0;
        for (int i = 0; i < n; i++) {
            int b = in.nextInt(), t = b + prev;
            res += Math.min(A[i], t);
            prev = Math.max(0, t - A[i]);
        }
        out.println(res + Math.min(A[n], prev));
    }

    private long gcd(long a, long b) {
        while (true) {
            if (b == 0) return a;
            long tmp = a;
            a = b;
            b = tmp % b;
        }
    }

    private int gcd(int a, int b) {
        while (true) {
            if (b == 0) return a;
            int tmp = a;
            a = b;
            b = tmp % b;
        }
    }

    private long powm(long x, long p) {
        long res = 1;
        while (p > 0) {
            if (p % 2 == 1)
                res = res * x % MOD;
            x = x * x % MOD;
            p /= 2;
        }
        return res;
    }

    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);
        // Scanner in = new Scanner(
                // new BufferedReader(new InputStreamReader(System.in)));
        FastScanner in = new FastScanner(System.in);

        Main sol = new Main(in, out);
        out.close();
    }
}

// Pair
class Pair<T extends Comparable<? super T>, U extends Comparable<? super U>> implements Comparable<Pair<T, U>> {
    T a;
    U b;
    Pair() { }
    Pair(T a, U b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public String toString() { return "("+a.toString()+", "+b.toString()+")"; }

    @Override
    public int hashCode() { return Objects.hash(a, b); }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if(obj == null) return false;
        if(this.getClass() != obj.getClass()) return false;
        Pair that = (Pair) obj;
        if(this.a.getClass() != that.a.getClass()) return false;
        if(this.b.getClass() != that.b.getClass()) return false;
        if(!this.a.equals(that.a)) return false;
        if(!this.b.equals(that.b)) return false;
        return true;
    }

    @Override
    public int compareTo(Pair<T, U> that) {
        int c = (this.a).compareTo(that.a);
        if(c == 0) c = (this.b).compareTo(that.b);
        return c;
    }
}

class FastScanner{
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public FastScanner(InputStream stream)
    {
        this.stream = stream;
    }

    int read()
    {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars){
            curChar = 0;
            try{
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    boolean isSpaceChar(int c)
    {
        return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
    }

    boolean isEndline(int c)
    {
        return c=='\n'||c=='\r'||c==-1;
    }

    int nextInt()
    {
        return Integer.parseInt(next());
    }

    long nextLong()
    {
        return Long.parseLong(next());
    }

    double nextDouble()
    {
        return Double.parseDouble(next());
    }

    String next(){
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do{
            res.appendCodePoint(c);
            c = read();
        }while(!isSpaceChar(c));
        return res.toString();
    }

    String nextLine(){
        int c = read();
        while (isEndline(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do{
            res.appendCodePoint(c);
            c = read();
        }while(!isEndline(c));
        return res.toString();
    }
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long[] a = new long[n + 1];
        long[] b = new long[n];
        for (int i = 0; i < n + 1; i++) {
            a[i] = sc.nextLong();
        }
        for (int i = 0; i < n; i++) {
            b[i] = sc.nextLong();
        }
        long ans = 0l;
        for (int i = 0; i < n; i++) {
            if(a[i] < b[i]) {
                ans += a[i];
                b[i] = b[i] - a[i];
                a[i] = 0;
            } else if(a[i] >= b[i]) {
                ans += b[i];
                b[i] = 0;
                a[i] = a[i] - b[i];
            }
            if(a[i + 1] < b[i]) {
                ans += a[i + 1];
                b[i] = b[i] - a[i + 1];
                a[i +1] = 0;
            } else if(a[i + 1] >= b[i]) {
                ans += b[i];
                b[i] = 0;
                a[i + 1] = a[i + 1] - b[i];
            }
        }
        System.out.println(ans);
    }
}


#include <cstdio>
using namespace std;

using i64 = long long;

#define REP(i, stop) for (int i = 0, i##_len = stop; i < i##_len; ++i)

const int cm = 1 << 17;
char cn[cm], *ci = cn + cm, ct;
inline char getc() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int read() {
	int r = 0;
	if (ci - cn + 16 > cm) while ((ct = getc()) & 16) r = r * 10 + ct - '0';
	else while ((ct = *ci++) & 16) r = r * 10 + ct - '0';
	return r;
}

// x shoud be greater than or equal to zero
inline void write(i64 x) {
	char d[20];
	int i = 0;
	while (true) {
		d[i] = x % 10 + 48;
		x /= 10;
		++i;
		if (x <= 0) break;
	}
	while (i--) {
		putchar(d[i]);
	}
}

int A[100001];
signed main() {
	int n = read();
	REP(i, n + 1) {
		A[i] = read();
	}
	i64 s = 0;
	int a0;
	int a1 = A[0];
	REP(i, n) {
		a0 = a1;
		a1 = A[i + 1];
		int b = read();
		int m = a0 < b ? a0 : b;
		s += m;
		b -= m;
		m = a1 < b ? a1 : b;
		s += m;
		a1 -= m;
	}
	write(s);
}


#include <cstdio>
using namespace std;

using i64 = long long;

#define REP(i, stop) for (int i = 0, i##_len = stop; i < i##_len; ++i)

int read() {
	int r = 0;
	while (true) {
		char c = getchar_unlocked();
		if (c & 16) {
			r = r * 10 + c - 48;
		} else {
			return r;
		}
	}
}

// x shoud be greater than or equal to zero
void write(i64 x) {
	char d[20];
	int i = 0;
	while (true) {
		d[i] = x % 10 + 48;
		x /= 10;
		++i;
		if (x <= 0) break;
	}
	while (i--) {
		putchar(d[i]);
	}
}

int A[100001];
signed main() {
	int n = read();
	REP(i, n + 1) {
		A[i] = read();
	}
	i64 s = 0;
	int a0;
	int a1 = A[0];
	REP(i, n) {
		a0 = a1;
		a1 = A[i + 1];
		int b = read();
		int m = a0 < b ? a0 : b;
		s += m;
		b -= m;
		m = a1 < b ? a1 : b;
		s += m;
		a1 -= m;
	}
	write(s);
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	int N = getint();
	int A[100001], B;
	rep(i, N + 1) A[i] = getint();

	ll kotae = 0;
	rep(i, N) {
		B = getint();
		int k = min(A[i], B);
		B -= k;
		kotae += k;
		k = min(A[i + 1], B);
		A[i + 1] -= k;
		kotae += k;
	}

	co(kotae);

	Would you please return 0;
}


#define debug 0
#include <bits/stdc++.h>
#define all(v) (v).begin(), (v).end()
#define pb push_back
#define rep(i,n) for(int i=0; i<(n); i++)
#define rep2(i,x,n) for(int i=x; i<(n); i++)
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
template<class t>using numr=std::numeric_limits<t>;
template<class t>bool chmax(t &a, const t &b) { if (a<b) { a=b; return 1; } return 0; }
template<class t>bool chmin(t &a, const t &b) { if (b<a) { a=b; return 1; } return 0; }
const int inf = 1e9;
const ll llinf = 1e16;
const int mod = 1000000007;
const int mod2 = 998244353;
void debug_impl() { std::cerr << std::endl; }
template <typename head, typename... tail>
void debug_impl(head head, tail... tail) { std::cerr << " " << head; debug_impl(tail...); }
#if debug
#define debug(...)\
    do {\
        std::cerr << std::boolalpha << "[" << #__va_args__ << "]:";\
        debug_impl(__va_args__);\
        std::cerr << std::noboolalpha;\
    } while (false)
#else
#define debug(...) {}
#endif

template < typename container, typename value = typename container::value_type, std::enable_if_t<!std::is_same< container, std::string >::value, std::nullptr_t> = nullptr>
std::istream& operator>> (std::istream& is, container& v)
    { for (auto & x : v) { is >> x; } return is; }

template < typename container, typename value = typename container::value_type, std::enable_if_t<!std::is_same< container, std::string >::value, std::nullptr_t> = nullptr >
std::ostream& operator<< (std::ostream& os, container const& v) {
os << "{";
    for (auto it = v.begin(); it != v.end(); it++)
        {os << (it != v.begin() ? "," : "") << *it;}
    return os << "}";
}

int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    int n;cin >> n;
    vector<int> a(n+1),b(n);
    cin >> a >> b;
    ll ans = 0;
    for(int i = 0;i<n;i++){
        int sub = min(a[i],b[i]);
        ans += sub;
        a[i] -= sub;
        b[i] -= sub;

        sub = min(b[i],a[i+1]);
        ans += sub;
        b[i] -= sub;
        a[i+1] -= sub;
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <deque>
using namespace std;
using Graph = vector<vector<int>>;

long long larger(long long a, long long b){
  if(a >= b){
    return a;
  }else{
    return b;
  }
}

long long smaller(long long a, long long b){
  if(a <= b){
    return a;
  }else{
    return b;
  }
}

int main() {
    //input
    int n; cin >> n;
    long long counter = 0;
    vector<long long> a(n + 2, 0);
    vector<long long> b(n + 2, 0);
    for(int i = 1; i < n + 2; i++) cin >> a[i];
    for(int i = 1; i < n + 1; i++) cin >> b[i];

    //compute
    for(int i = 1; i < n + 2; i++){
        counter += smaller(a[i] + a[i + 1],b[i]);
        a[i + 1] = smaller(0 , a[i + 1] - larger(0, b[i] - a[i]));
    }

    //output
    cout << counter << endl;
}


#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <deque>
using namespace std;
using Graph = vector<vector<int>>;

long long larger(long long a, long long b){
  if(a >= b){
    return a;
  }else{
    return b;
  }
}

long long smaller(long long a, long long b){
  if(a <= b){
    return a;
  }else{
    return b;
  }
}

int main() {
    //input
    int n; cin >> n;
    long long counter = 0;
    vector<long long> a(n + 2, 0);
    vector<long long> b(n + 2, 0);
    for(int i = 1; i < n + 2; i++) cin >> a[i];
    for(int i = 1; i < n + 1; i++) cin >> b[i];

    //compute
    for(int i = 1; i < n + 2; i++){
        counter += smaller(a[i] + a[i + 1],b[i]);
        a[i + 1] -= smaller(0 , a[i + 1] - larger(0, b[i] - a[i]));
    }

    //output
    cout << counter << endl;
}


// AtCoder ABC135: C - City Savers
// 2019.8.26 bal4u

#include <stdio.h>

typedef long long ll;

//// 高速入力
#define gc() getchar_unlocked()

int in() {   // 非負整数の入力
	int n = 0, c = gc();
	do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0');
	return n;
}

int a[100005];
int b[100005];

int main()
{
	int i, p, N; ll ans;

	N = in();
	for (i = 0; i <= N; i++) a[i] = in();
	for (i = 0; i <  N; i++) b[i] = in();
	ans = 0; p = 0;
	for (i = 0; i <= N; i++) {
		if (p >= a[i]) ans += a[i], p = b[i];
		else if (p+b[i] <= a[i]) ans += p+b[i], p = 0;
		else ans += a[i], p = b[i]-(a[i]-p);
	}
	printf("%lld\n", ans);
	return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void){
  int N,i;
  long a[100005],b[100005],count;
  char str[5000000],*p;

  fgets(str,sizeof(str),stdin);
  N=atoi(str);

  fgets(str,sizeof(str),stdin);
  p=strtok(str," \n");
  a[0]=atol(p);

  for(i=1;i<N+1;i++){
    p=strtok(NULL," \n");
  	a[i]=atol(p);
  }

  fgets(str,sizeof(str),stdin);
  p=strtok(str," \n");
  b[0]=atol(p);

  for(i=1;i<N;i++){
    p=strtok(NULL," \n");
  	b[i]=atol(p);
  }

  for(i=0;i<N;i++){
    if(a[i]>=b[i]){
      count+=b[i];
    }else{
      b[i]-=a[i];
      count+=a[i];
      if(b[i]>=a[i+1]){
        count+=a[i+1];
        a[i+1]=0;
      }else{
        a[i+1]-=b[i];
        count+=b[i];
      }
    }
  }

  printf("%ld\n",count);

  return 0;
}


#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 内部定数
#define D_TOWN_MAX		100005									// 最大街数

// 内部変数
static FILE *szpFpI;											// 入力
static int si1MCnt[D_TOWN_MAX];									// モンスター数[街]
static int si1WCnt[D_TOWN_MAX];									// 討伐数[街]
static int siTCnt;												// 街数

// 内部変数 - テスト用
#ifdef D_TEST
	static int siRes;
	static FILE *szpFpA;
	static int siTNo;
#endif

// 出力
int
fOut(
	char *pcpLine				// <I> １行
)
{
	char lc1Buf[1024];

#ifdef D_TEST
	fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
	if (strcmp(lc1Buf, pcpLine)) {
		siRes = -1;
	}
#else
	printf("%s", pcpLine);
#endif

	return 0;
}

// 実行メイン
long long
fMain(
)
{
	int i;
	char lc1Buf[1024];

	// 街数 - 取得
	fgets(lc1Buf, sizeof(lc1Buf), szpFpI);
	sscanf(lc1Buf, "%d", &siTCnt);
	siTCnt++;

	// モンスター数 - 取得
	for (i = 0; i < siTCnt; i++) {
		fscanf(szpFpI, "%d", &si1MCnt[i]);
	}
	fgets(lc1Buf, sizeof(lc1Buf), szpFpI);

	// 討伐数 - 取得
	for (i = 0; i < siTCnt - 1; i++) {
		fscanf(szpFpI, "%d", &si1WCnt[i]);
	}
	fgets(lc1Buf, sizeof(lc1Buf), szpFpI);

	// 合計数 - 取得
	long long llSum = 0;
	for (i = 0; i < siTCnt - 1; i++) {

		// 自分の街
		if (si1MCnt[i] < si1WCnt[i]) {
			llSum += si1MCnt[i];
			si1WCnt[i] -= si1MCnt[i];
		}
		else {
			llSum += si1WCnt[i];
			si1WCnt[i] = 0;
		}

		// 先の街
		if (si1MCnt[i + 1] < si1WCnt[i]) {
			llSum += si1MCnt[i + 1];
			si1MCnt[i + 1] = 0;
		}
		else {
			llSum += si1WCnt[i];
			si1MCnt[i + 1] -= si1WCnt[i];
		}
	}

	return llSum;
}

// １回実行
int
fOne(
)
{
	long long llRet;
	char lc1Buf[1024];

	// 入力 - セット
#ifdef D_TEST
	sprintf(lc1Buf, ".\\Test\\T%d.txt", siTNo);
	szpFpI = fopen(lc1Buf, "r");
	sprintf(lc1Buf, ".\\Test\\A%d.txt", siTNo);
	szpFpA = fopen(lc1Buf, "r");
	siRes = 0;
#else
	szpFpI = stdin;
#endif

	// 実行メイン
	llRet = fMain();

	// 出力
	sprintf(lc1Buf, "%lld\n", llRet);
	fOut(lc1Buf);

	// 残データ有無
#ifdef D_TEST
	lc1Buf[0] = '\0';
	fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
	if (strcmp(lc1Buf, "")) {
		siRes = -1;
	}
#endif

	// テストファイルクローズ
#ifdef D_TEST
	fclose(szpFpI);
	fclose(szpFpA);
#endif

	// テスト結果
#ifdef D_TEST
	if (siRes == 0) {
		printf("OK %d\n", siTNo);
	}
	else {
		printf("NG %d\n", siTNo);
	}
#endif

	return 0;
}

// プログラム開始
int
main()
{

#ifdef D_TEST
	int i;
	for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) {
		siTNo = i;
		fOne();
	}
#else
	fOne();
#endif

	return 0;
}


#include <stdio.h>
#include <stdlib.h>

int	min(int a, int b)
{
	return (a < b ? a : b);
}

int	main(void)
{
	int	N;
	int	*A, *B, *C;
	int	i;
	int	res;

	scanf("%d", &N);
	A = malloc(sizeof(int) * (N + 1));
	B = malloc(sizeof(int) * N);
	C = malloc(sizeof(int) * N);
	for (i = 0; i < N + 1; i++)
		scanf("%d", &A[i]);
	for (i = 0; i < N; i++)
		scanf("%d", &B[i]);
	C[0] = min(A[0] + A[1], B[0]);
	A[1] = A[1] + min(A[0] - B[0], 0);
	for (i = 0; i < N; i++)
	{
		C[i] = min(A[i] + A[i + 1], B[i]);
		A[i + 1] -= min(A[i] - B[i], 0);
	}
	res = 0;
	for (i = 0; i < N; i++)
		res += C[i];
	printf("%d\n", res);
	free(A);
	free(B);
	return (0);
}


#include <stdio.h>

int main(){
  int N;
  long long int A[200000],B[200000];
  long long int S=0LL;
  scanf("%d",&N);
  for(int i=1;i<=N+1;i++)
    scanf("%lld",A+i);
  for(int i=1;i<=N;i++)
    scanf("%lld",B+i);
  B[N+1]=0LL;
  for(int i=1;i<=N+1;i++){
    S+=A[i]>=B[i]?B[i]:A[i];
    B[i+1]+=A[i]>=B[i]?0:B[i]-A[i];
  }
  printf("%lld\n",S);
  return 0;
}


#pragma warning(disable:4996)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <float.h>

#pragma region 定義
typedef long long  ll;
typedef unsigned long long  ull;

#define _itoa(A,N) sprintf(A, "%d", N);

int i_dsort(const void* a, const void* b);
int i_asort(const void* a, const void* b);

int  _gcd(int a, int b);
int  _swp(int* a, int* b);
int _cknum(char* a, int n);
int _atoi(char* s, int len);

int s_asort(const void* a, const void* b);
int s_dsort(const void* a, const void* b);

//昇順
int s_asort(const void* a, const void* b) {
	return(strcmp((char*)a, (char*)b));
}
int s_dsort(const void* a, const void* b) {
	return(strcmp((char*)b, (char*)a));
}

int i_dsort(const void* a, const void* b) {
	return(*(int*)b - *(int*)a);
}
int i_asort(const void* a, const void* b) {
	return(*(int*)a - *(int*)b);
}

int _gcd(int a, int b) {
	int r, tmp;
	if (a < b) { tmp = a; a = b; b = tmp; }
	r = a % b;
	while (r) {
		if (!r) break;
		a = b; b = r;
		r = a % b;
	}
	return(b);
}
// puts("Yes\n") puts("No\n")
// scanf("%d.%d") 浮動小数点入力を整数２つで得る

//#define pai  3.1415926535
//#define  _USE_MATH_DEFINES でM_PIが使える

#define deg_rad(X)  (X*(M_PI/180))

int _swp(int* a, int* b)
{
	int tmp;
	tmp = *b; *b = *a; *a = tmp;
	return 0;
}
#define _abs(x) ((x)>0?(x):-(x))
#define _min(x,y) ((x)<(y)?(x):(y))
#define _max(x,y) ((x)<(y)?(y):(x))

int _cknum(char* a, int n) {
	int i;
	char t = '0';

	for (i = 0; i < n; i++) {
		if (a[i] < '0' || a[i]>'9') return 1;
	}
	return 0;
}

int _atoi(char* s, int len) {
	char tmp[20];
	memcpy(tmp, s, len);
	tmp[len] = 0x00;
	return (atoi(tmp));
}

//素因数分解　pf素数が入る　pc 素数の数
ll _pfact(ll a);
static ll pf[100000000];
static ll pc;

ll _pfact(ll a) {
	long i, r;
	if (a % 2 == 0) {
		pf[pc] = 2; pc++;
		return(_pfact(a / 2));
	}
	r = sqrt(a);
	for (i = 3; i <= r; i += 2) {
		if (a % i == 0) {
			pf[pc] = i; pc++;
			return(_pfact(a / i));
		}
	}
	if (a != 1) {
		pf[pc] = a; pc++;
	}
	return 0;

}

#pragma endregion

//ABC 135 -C City Saver
#define MAX 100001
//#define MAX 101
int cnt_m(int* a, int* b, int* ans);
int cnt_m(int* a, int* b, ll* ans) {
	if (*a >= *b) {
		*ans += *b;
		*a -= *b;
		return 0;
	}

	*ans += *a;
	*b -= *a;
	*a = 0;
	return 1;
}

int main(void) {
	int n, i;
	ll  ans = 0;
	int a[MAX], b[MAX];

	scanf("%d", &n);

	for (i = 0; i < n+1; i++)
		scanf("%d", &a[i]);

	for (i = 0; i < n; i++)
		scanf("%d", &b[i]);

	int rc = 0;
	for (i = 0; i < n; i++) {
		rc = cnt_m(&a[i], &b[i], &ans);
//		printf("\n%d ", ans);
		if (rc == 0) continue;
		if (i + 1 > n) break;
		rc = cnt_m(&a[i + 1], &b[i], &ans);
//		printf("\n%d ", ans);
	}
	printf("%lld\n", ans);
	return 0;
}


function Main(input) {
    input = input.split("\n");
    N = Number(input[0])
    tmpi = input[1].split(" ");
    tmpj = input[2].split(" ");
    an = 0;
    for(i = 0; i < N; i++){
        yusha = Number(tmpj[i]);
        mons = Number(tmpi[i]);
        c = yusha - mons;
        if(c >= 0) an += mons;
        else an += yusha;
        if(c <= 0) continue;
        d = Number(tmpi[i+1]) - c;
        if(d >= 0){an += c;tmpi[i+1] =d}
        else{an+=Number(tmpi[i+1]);tmpi[i+1] =0}
    }
    console.log(an);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {

	// 1行目がinput[0], 2行目がinput[1], …に入る
  input = input.split("\n");
  var n = input[0];
  var n= parseInt(input[0], 10);

  var A = input[1].split(" ");
  var a = [];
for (var i = 0; i < n+1; i++) {
  var r= parseInt(A[i], 10);
  a[i] = r; }
 // console.log(a);

   var B = input[2].split(" ");
  var b = [];
for (var i = 0; i < n; i++) {
  var r= parseInt(B[i], 10);
  b[i] = r; }
 // console.log(b);

 var i = 0;
  var m = 0;
  var mon =  a[i];
  for (var i = 0;i<n;i++){if(mon>=b[i]){m = m + b[i];
                                         mon = a[i+1];}
                            else {mon = mon + a[i+1] ;
                                  if (mon>=b[i]){m = m + b[i];
                               //   console.log(m);
                                              mon = mon-b[i];}
                                              else{m= m + mon;
                                                   var mon = 0;
                                          //    console.log(m);}
                                              }
                                              }
                                              }

 console.log(m);
     }
  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	A1 = input[1].split(" ");
  	B1 = input[2].split(" ");
	//文字列から10進数に変換するときはparseIntを使います
	var N = parseInt(input[0], 10);
  	var i = 0;
  	var aCount = 0;
  	var j = 0;
  	while(i < N){
      	var A = parseInt(A1[i]);
      	var B = parseInt(B1[i]);
      	aCount = aCount + Math.min(A, j + B);
      	if(B > (A - j)){
        	j = B - Math.max(A - j, 0);
        }else{
        	j = 0;
        }
    	i = i + 1;
    }
	var A = parseInt(A1[i]);
  	aCount = aCount + Math.min(A, j);

	console.log('%d',aCount);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  input=input.split("\n");
  if(input[input.length-1]===''){
    input.pop();
  }
  const N=input[0]-0;
  const A=input[1].split(' ').map(e=>{
    return e-0;
  });
  const B=input[2].split(' ').map(e=>{
    return e-0;
  });
  var ret=0;
  var remain=0;
  for(var i=0;i<N;i++){
    ret+=Math.min(A[i],remain+B[i]);
    remain=remain+B[i]-Math.min(A[i],remain+B[i]);
  }
  ret+=Math.min(remain,A[N]);
  console.log(ret);

}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var N = nextInt();
	var alist = nextIntArray();
	var blist = nextIntArray();
	var output = 0;
	for(var i = 0; i < N; i++){
		if(alist[i] <= blist[i]){
			output += alist[i];
			blist[i] -= alist[i];
			output += Math.min(alist[i + 1], blist[i]);
			alist[i + 1] -= Math.min(blist[i],0);
		}else{
			output += blist[i];
		}
	}
	myout(output);
}


//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var N = nextInt();
	var alist = nextIntArray();
	var blist = nextIntArray();
	var output = 0;
	for(var i = 0; i < N; i++){
		if(alist[i] <= blist[i]){
			output += alist[i];
			blist[i] -= alist[i];
			output += Math.min(alist[i + 1], blist[i]);
			alist[i + 1] -= Math.min(blist[i],0);
		}else{
			output += blist[i];
		}
		myerr(alist);
		myerr(blist);
	}
	myout(output);
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var sc = bufio.NewScanner(os.Stdin)

const inf = 1 << 60
const mod int = 1e9 + 7

func ri() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func main() {
	sc.Split(bufio.ScanWords)
	n := ri()
	a := make([]int, n+1)
	for i := range a {
		a[i] = ri()
	}
	b := make([]int, n)
	for i := range b {
		b[i] = ri()
	}
	a = append(a, 0)
	b = append(b, 0)
	ct := 0
	for i := 0; i <= n; i++ {
		if b[i] <= a[i] {
			ct += b[i]
			b[i] = 0
		} else {
			ct += a[i]
			b[i] -= a[i]
			a[i] = 0
			if b[i] <= a[i+1] {
				ct += b[i]
				a[i+1] -= b[i]
			} else {
				ct += a[i+1]
				b[i] -= a[i+1]
				a[i+1] = 0
			}
		}
	}
	fmt.Println(ct)
}


// Template: https://github.com/maitaken/atcoder-template
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

const (
	BUFSIZE = 10000000
	MOD     = 1000000007
	INT_INF = math.MaxInt32
)

var rdr *bufio.Reader

func main() {
	rdr = bufio.NewReaderSize(os.Stdin, BUFSIZE)
	solve()
}

func solve() {
	readint()
	A := readIntSlice()
	B := readIntSlice()

	ans := 0
	for i, v := range B {
		if A[i] > v {
			ans += v
		} else {
			ans += A[i]
			v -= A[i]
			ans += min(v, A[i+1])
			A[i+1] -= min(v, A[i+1])
		}
	}
	fmt.Println(ans)

}

func readline() string {
	buf := make([]byte, 0, 16)
	for {
		l, p, e := rdr.ReadLine()
		if e != nil {
			fmt.Println(e.Error())
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

func readIntSlice() []int {
	slice := make([]int, 0)
	lines := strings.Split(readline(), " ")
	for _, v := range lines {
		slice = append(slice, s2i(v))
	}
	return slice
}

func readint() int {
	return s2i(readline())
}

func readint2() (int, int) {
	lines := strings.Split(readline(), " ")
	return s2i(lines[0]), s2i(lines[1])
}

func readint3() (int, int, int) {
	lines := strings.Split(readline(), " ")
	return s2i(lines[0]), s2i(lines[1]), s2i(lines[2])
}

func readint4() (int, int, int, int) {
	lines := strings.Split(readline(), " ")
	return s2i(lines[0]), s2i(lines[1]), s2i(lines[2]), s2i(lines[3])
}

// For int
func b2i(b bool) int {
	if b {
		return 1
	}
	return 0
}

func abs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}

func pow(x, y int) int {
	return int(math.Pow(float64(x), float64(y)))
}

func mod(x, y int) int {
	m := x % y
	if m < 0 {
		return m + y
	}
	return m
}

func modpow(x, y int) int {
	ret := 1
	for ; y != 0; y >>= 1 {
		if y&1 == 1 {
			ret = mod((ret * x), MOD)
		}
		x = mod(x*x, MOD)
	}
	return ret
}

func min(values ...int) int {
	ret := INT_INF
	for _, v := range values {
		if ret > v {
			ret = v
		}
	}
	return ret
}

func max(values ...int) int {
	ret := -INT_INF
	for _, v := range values {
		if ret < v {
			ret = v
		}
	}
	return ret
}

func s2i(s string) int {
	v, ok := strconv.Atoi(s)
	if ok != nil {
		panic("Faild : " + s + " can't convert to int")
	}
	return v
}

func i2s(i int) string {
	return strconv.Itoa(i)
}

func gcd(v1, v2 int) int {
	if v1 > v2 {
		v1, v2 = v2, v1
	}
	for v1 != 0 {
		v1, v2 = v2%v1, v1
	}
	return v2
}

func lcm(v1, v2 int) int {
	return v1 * v2 / gcd(v1, v2)
}

func extgcd(a, b, c int) (int, int, int) {
	if a < b {
		a, b = b, a
	}
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := extgcd(b, mod(a, b), c)
	return d, y, x - int(a/b)*y
}

func bit(size int) [][]bool {
	bSize := int(math.Pow(2, float64(size)))
	b := make([][]bool, bSize)
	for i := 0; i < bSize; i++ {
		b[i] = make([]bool, size)
		for j := 0; j < size; j++ {
			if i>>j&1 == 1 {
				b[i][j] = true
			} else {
				b[i][j] = false
			}
		}
	}
	return b
}

/* ------------------------------------------------ */
/* Data stracture                                   */
/* ------------------------------------------------ */
// 簡易的なDeque (PushLeftが非常に遅い)
type Deque []interface{}

func (q *Deque) PopRight() (r interface{}) {
	l := len(*q)
	r = (*q)[l-1]
	*q = (*q)[:l-1]
	return
}

func (q *Deque) PopLeft() (r interface{}) {
	r = (*q)[0]
	*q = (*q)[1:]
	return
}

func (q *Deque) PushRight(x interface{}) {
	*q = append(*q, x)
}

func (q *Deque) PushLeft(x interface{}) {
	*q = append([]interface{}{x}, *q...)
}

type IntHeap []int

func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

// BIT Tree
type FenwickTree []int

func NewFenwickTree(size int) *FenwickTree {
	var t FenwickTree
	t = make([]int, size+1)
	return &t
}

func (t FenwickTree) add(index, v int) {
	for i := index + 1; i < len(t); i += (i & -i) {
		t[i] += v
	}
}

func (t FenwickTree) sum(index int) int {
	total := 0
	for i := index + 1; i != 0; i -= (i & -i) {
		total += t[i]
	}
	return total
}

type Comb struct {
	length int
	fac    []int
	inv    []int
	finv   []int
}

func NewComb() *Comb {
	return &Comb{
		length: 2,
		fac:    []int{1, 1},
		inv:    []int{1, 1},
		finv:   []int{1, 1},
	}
}

func (c Comb) calc(n, k int) int {
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}

	if c.length <= n {
		for i := c.length; i <= n; i++ {
			c.fac = append(c.fac, mod(c.fac[i-1]*i, MOD))
			c.inv = append(c.inv, MOD-mod(c.inv[mod(MOD, i)]*(MOD/i), MOD))
			c.finv = append(c.finv, mod(c.finv[i-1]*c.inv[i], MOD))
		}
	}
	return mod(c.fac[n]*mod(c.finv[k]*c.finv[n-k], MOD), MOD)
}


package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

const (
	initialBufSize = 100000
	maxBufSize     = 1000000
)

var sc *bufio.Scanner

func initScanner(r io.Reader) *bufio.Scanner {
	buf := make([]byte, initialBufSize)

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	return sc
}

func main() {
	sc = initScanner(os.Stdin)
	fmt.Println(resolve(parseProblem()))
}

func parseProblem() int {
	n := scanInt(sc)
	as := nextIntSlice(sc, n+1)
	bs := nextIntSlice(sc, n)
	num := 0
	rest := as[0]
	for i := 0; i < len(bs); i++ {
		monsters := rest + as[i+1]
		killNum := min(monsters, bs[i])
		num += killNum
		if killNum > rest {
			rest = as[i+1] - (killNum - rest)
		} else {
			rest = as[i+1]
		}
	}
	return num
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func nextInt(sc *bufio.Scanner) int {
	sc.Scan()
	a, _ := strconv.Atoi(sc.Text())
	return int(a)
}

func nextString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

func nextIntSlice(sc *bufio.Scanner, n int) (a []int) {

	a = make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = nextInt(sc)
	}
	return a
}

func resolve(n int) int {
	return n
}

// snip-scan-funcs
func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}
func scanString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	// Code for C - City Savers
	var N int
	fmt.Scanf("%d", &N)

	sc.Split(bufio.ScanWords)
	A := make([]int, N+1)
	B := make([]int, N)

	for i := 0; i < N+1; i++ {
		A[i] = nextInt()
	}

	for i := 0; i < N; i++ {
		B[i] = nextInt()
	}

	var ans int
	var temp int = 0
	for i := 0; i < N; i++ {
		if A[i] <= temp {
			temp = A[i]
			A[i] = 0
		} else {
			A[i] = A[i] - temp
		}

		if A[i] <= B[i] {
			ans += A[i] + temp
			temp = B[i] - A[i]
		} else {
			ans += B[i]
			temp = 0
		}
	}

	if temp != 0 {
		if temp <= A[N] {
			ans += temp
		} else {
			ans += A[N]
		}
	}

	fmt.Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	// Code for C - City Savers
	var N int
	fmt.Scanf("%d", &N)

	sc.Split(bufio.ScanWords)
	A := make([]int, N+1)
	B := make([]int, N)

	for i := 0; i < N+1; i++ {
		A[i] = nextInt()
	}

	for i := 0; i < N; i++ {
		B[i] = nextInt()
	}

	var ans int
	var temp int = 0
	for i := 0; i < N; i++ {
		if A[i] < temp {
			temp = A[i]
			A[i] = 0
		} else {
			A[i] = A[i] - temp
		}

		if A[i] <= B[i] {
			ans += A[i] + temp
			temp = B[i] - A[i]
		} else {
			ans += B[i]
			temp = 0
		}
		//fmt.Println(ans)
	}

	if temp != 0 {
		if temp <= A[N] {
			ans += temp
		} else {
			ans += A[N]
		}
	}

	fmt.Println(ans)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	getStdinInt64()
	A := getStdinIntArr64()
	B := getStdinIntArr64()

	var i int64 = 0
	var ans int64 = 0
	for ; i < int64(len(A)); i++ {
		var tmp int64 = 0
		if i == 0 {
			if B[i] >= A[i] {
				tmp += A[i]
			} else {
				tmp += B[i]
			}
			B[i] -= tmp
		} else if i < int64(len(B)) {
			if B[i-1]+B[i] >= A[i] {
				tmp += A[i]
				B[i] -= A[i] - B[i-1]
			} else {
				tmp += B[i-1] + B[i]
				B[i] -= tmp - B[i-1]
			}
		} else {
			if B[i-1] >= A[i] {
				tmp += A[i]
			} else {
				tmp += B[i-1]
			}
			//B[i] -= tmp
		}
		ans += tmp
	}
	fmt.Printf("%d\n", ans)
}

var sc = bufio.NewReaderSize(os.Stdin, 1024*1024*10)

func getStdin() string {
	return readLine()
}
func getStdinInt() int {
	str := getStdin()
	rtn, _ := strconv.Atoi(str)
	return rtn
}
func getStdinInt2() (int, int) {
	list := getStdinIntArr()
	return list[0], list[1]
}
func getStdinInt3() (int, int, int) {
	list := getStdinIntArr()
	return list[0], list[1], list[2]
}
func getStdinInt4() (int, int, int, int) {
	list := getStdinIntArr()
	return list[0], list[1], list[2], list[3]
}
func getStdinInt64() int64 {
	str := getStdin()
	rtn, _ := strconv.ParseInt(str, 10, 64)
	return rtn
}
func getStdinInt64_2() (int64, int64) {
	list := getStdinIntArr64()
	return list[0], list[1]
}
func getStdinInt64_3() (int64, int64, int64) {
	list := getStdinIntArr64()
	return list[0], list[1], list[2]
}
func getStdinIntArr() []int {
	str := getStdin()
	list := strings.Split(str, " ")
	rtn := make([]int, len(list))
	for idx, val := range list {
		rtn[idx], _ = strconv.Atoi(val)
	}
	return rtn
}
func getStdinIntArr64() []int64 {
	str := getStdin()
	list := strings.Split(str, " ")
	rtn := make([]int64, len(list))
	for idx, val := range list {
		rtn[idx], _ = strconv.ParseInt(val, 10, 64)
	}
	return rtn
}
func readLine() string {
	buf := make([]byte, 0, 0)
	for {
		l, p, _ := sc.ReadLine()
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}


N = gets.chomp.to_i
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)
score = 0
old = 0

0.upto(N) do |i|
  enemy = A[i]
  hero = B[i] || 0

  if enemy <= old
    score += enemy
    old = hero
    next
  else
    enemy -= old
    score += old
  end

  if enemy <= hero
    score += enemy
    old = hero - enemy
  else
    score += hero
    old = 0
  end
end

puts score


N = gets.to_i
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)

ret = 0
remain = A[0]
N.times do |i|
  if remain <= B[i]
    power = B[i] - remain
    ret += remain
    if A[i + 1] <= power
      remain = 0
      ret += A[i + 1]
    else
      remain = A[i + 1] - power
      ret += power
    end
  else
    ret += B[i]
    remain = A[i + 1]
  end
end
puts ret


n = gets.chomp.to_i
a_arr = gets.chomp.split(" ").map(&:to_i)
b_arr = gets.chomp.split(" ").map(&:to_i)

count = 0
b_arr.each_with_index do |b, i|
  a = a_arr[i]
  if b <= a then
    count += b
  else
    count += a
    next_b = b - a
    next_a = a_arr[i+1]
    if next_b <= next_a then
      count += next_b
      a_arr[i+1] = next_a - next_b
    else
      count += next_a
      a_arr[i+1] = 0
    end
  end
end
puts count


n=gets.to_i
s=gets.split.map &:to_i
a=gets.split.map &:to_i
sum=0
for i in 0..n-1
  if s[i]<a[i]
    sum+= (a[i]>=(s[i]+s[i+1]))? (s[i]+s[i+1]):a[i]
    s[i+1]-= a[i]-s[i]
    s[i+1]=0 if s[i+1]<=0
  else
    sum+=s[i]
  end
end
puts sum


n=gets.to_i
s=gets.split.map &:to_i
a=gets.split.map &:to_i
sum=0
for i in 0..n-1
  if s[i]<a[i]
    sum+= (a[i]>=(s[i]+s[i+1]))? (s[i]+s[i+1]):a[i]
    s[i+1]-= a[i]-s[i]
    s[i+1]=0 if s[i+1]<=0
  else
    sum+=s[i]
  end
end
p s


n = gets.to_i
a = gets.strip.split.map(&:to_i)
b = gets.strip.split.map(&:to_i)

sum = 0
i = 0
s = b[0]
while i<n-1 do
  if a[i]>=s
    sum += s
    s = b[i+1]
  else
    sum += a[i]
    s = b[i+1]+(s-a[i])
  end
  i += 1
end
sum += [s,a[n-1]+a[n]].min

c = a.reverse
d = b.reverse
tum = 0
i = 0
s = d[0]
while i<n-1 do
  if c[i]>=s
    tum += s
    s = d[i+1]
  else
    tum += c[i]
    s = d[i+1]+(s-c[i])
  end
  i += 1
end
tum += [s,c[n-1]+c[n]].min

puts [sum,tum].min


use std::cmp::*;
use std::io::*;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

pub fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let n = i.read::<usize>();
    let a = i.read_vec::<usize>(n + 1);
    let b = i.read_vec::<usize>(n);
    writeln!(o, "{}", solve(&a, &b)).unwrap();
}
fn solve(a: &[usize], b: &[usize]) -> usize {
    let mut ans = 0;
    let mut bp = 0;

    for i in 0..b.len() {
        let x0 = min(a[i], bp);
        ans += x0;
        let a = a[i] - x0;

        let x1 = min(b[i], a);
        ans += x1;
        bp = b[i] - x1;
    }
    ans += min(a[b.len()], bp);
    ans
}

pub mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        b: Vec<u8>,
    }
    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                b: Vec::new(),
            }
        }
        pub fn read_word(&mut self) -> &[u8] {
            self.b.clear();
            let mut consume = 0;
            loop {
                self.r.consume(consume);
                let b = self.r.fill_buf().unwrap();
                assert!(b.len() != 0);
                if let Some(p) = b.iter().position(|&x| x == b' ' || x == b'\n') {
                    self.b.extend_from_slice(&b[..p]);
                    consume = p + 1;
                    break;
                }
                self.b.extend_from_slice(b);
                consume = b.len();
            }
            self.r.consume(consume);
            &self.b
        }
        pub fn read_word_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_word()) }
        }

        pub fn read_line(&mut self) -> &[u8] {
            self.b.clear();
            self.r.read_until(b'\n', &mut self.b).unwrap();
            if self.b.last() == Some(&b'\n') {
                &self.b[..self.b.len() - 1]
            } else {
                &self.b
            }
        }
        pub fn read_line_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_line()) }
        }

        pub fn read<T: CpIn>(&mut self) -> T {
            T::read_from(self)
        }

        pub fn read_vec<T: CpIn>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read()).collect()
        }
        pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {
            CpIter {
                r: self,
                n: n,
                _pd: Default::default(),
            }
        }
    }
    pub struct CpIter<'a, R: BufRead + 'a, T> {
        r: &'a mut CpReader<R>,
        n: usize,
        _pd: std::marker::PhantomData<fn() -> T>,
    }
    impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            if self.n == 0 {
                None
            } else {
                self.n -= 1;
                Some(self.r.read())
            }
        }
    }

    pub trait CpIn {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self;
    }

    impl CpIn for u64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_u64_fast(&mut r.r)
        }
    }
    impl CpIn for i64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_i64_fast(&mut r.r)
        }
    }
    impl CpIn for char {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            let b = r.r.fill_buf().unwrap()[0] as char;
            r.r.consume(1);
            let s = r.r.fill_buf().unwrap()[0];
            assert!(s == b' ' || s == b'\n');
            r.r.consume(1);
            b
        }
    }

    macro_rules! cpin_tuple {
        ($($t:ident),*) => {
            impl<$($t: CpIn),*> CpIn for ($($t),*) {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    ($($t::read_from(r)),*)
                }
            }
        };
    }

    macro_rules! cpin_cast {
        ($t_self:ty, $t_read:ty) => {
            impl CpIn for $t_self {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    <$t_read>::read_from(r) as $t_self
                }
            }
        };
    }
    macro_rules! cpin_parse {
        ($t:ty) => {
            impl CpIn for $t {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    r.read_word_str().parse().unwrap()
                }
            }
        };
    }
    cpin_cast!(usize, u64);
    cpin_cast!(u32, u64);
    cpin_cast!(u16, u64);
    cpin_cast!(i32, i64);
    cpin_cast!(i16, i64);
    cpin_cast!(i8, i64);

    cpin_parse!(f64);

    cpin_tuple!(T1, T2);
    cpin_tuple!(T1, T2, T3);
    cpin_tuple!(T1, T2, T3, T4);
    cpin_tuple!(T1, T2, T3, T4, T5);

    fn read_u64_fast<R: BufRead>(r: &mut R) -> u64 {
        let mut value = 0;
        loop {
            let mut idx = 0;
            let buf_len;
            {
                let buf = r.fill_buf().unwrap();
                buf_len = buf.len();
                assert!(buf_len != 0);
                while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {
                    value = value * 10 + (buf[idx] - b'0') as u64;
                    idx += 1;
                }
            }
            if idx < buf_len {
                r.consume(idx + 1);
                return value;
            }
            r.consume(idx);
        }
    }
    fn read_i64_fast<R: BufRead>(r: &mut R) -> i64 {
        let (consume, sign) = match r.fill_buf().unwrap()[0] {
            b'+' => (true, 1),
            b'-' => (true, -1),
            _ => (false, 1),
        };
        if consume {
            r.consume(1);
        }
        read_u64_fast(r) as i64 * sign
    }

}


/*------------------------------------------------------------------*/
/*------------------------- begin template -------------------------*/
/*------------------------------------------------------------------*/

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, char_) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()[0]
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, i64_) => {
        $parser.fast_i64()
    };
    ($parser:ident, usize_) => {
        $parser.fast_i64() as usize
    };
    ($parser:ident, usize1_) => {
        ($parser.fast_i64() - 1) as usize
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

use std::io;
use std::io::BufRead;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    pub reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R: BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len, complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len - 1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.parse::<T>();
            } else {
                self.update_buf();
            }
        }
    }
    pub fn fast_i64(&mut self) -> i64 {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            if begin == self.buf.len() {
                self.update_buf();
                continue;
            }
            let mut res = 0;
            let (is_positive, mut end) = match self.buf[begin] {
                b'+' => (true, begin + 1),
                b'-' => (false, begin + 1),
                _ => (true, begin),
            };
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                res = res * 10 + (self.buf[end] as i64 - '0' as i64);
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return if is_positive { res } else { -res };
            } else {
                self.update_buf();
            }
        }
    }
}

#[allow(unused_imports)]
use std::cmp::*;

fn main() {
    input! {
        new_stdin_parser = parser,
    }
    let res = solve(&mut parser);
    print!("{}", res);
}

/*------------------------------------------------------------------*/
/*-------------------------- end template --------------------------*/
/*------------------------------------------------------------------*/

use std::fmt::Write;
fn solve<R: BufRead>(parser: &mut Parser<R>) -> String {
    let mut buf = String::new();
    input! {
        parser = parser,
        n: usize,
        xs: [i64; n+1],
        ys: [i64; n],
    }
    let mut xs = xs;
    let mut ys = ys;
    let mut res = 0;
    for i in 0..n {
        let r = min(xs[i], ys[i]);
        xs[i] -= r;
        ys[i] -= r;
        res += r;
        let r = min(xs[i + 1], ys[i]);
        xs[i + 1] -= r;
        ys[i] -= r;
        res += r;
    }
    writeln!(buf, "{}", res);
    buf
}


use std::io::*;

const SP: u8 = b' ';
const LF: u8 = b'\n';

struct CharacterInput<'a> {
    locked_stdin: StdinLock<'a>,
    bytes_buffer: Vec<u8>,
}

impl<'a> CharacterInput<'a> {
    fn read(&mut self, delimiter: u8) -> &[u8] {
        self.bytes_buffer.clear();

        let len = self
            .locked_stdin
            .read_until(delimiter, &mut self.bytes_buffer)
            .unwrap();

        let end_index = match self.bytes_buffer.last() {
            Some(byte) => {
                if *byte == delimiter {
                    len - 1
                } else {
                    len
                }
            }
            None => len,
        };

        &self.bytes_buffer[0..end_index]
    }

    fn scan_u(&mut self, delimiter: u8) -> u64 {
        self.read(delimiter)
            .into_iter()
            .fold(0, |accumulator, byte| {
                (byte - b'0') as u64 + accumulator * 10
            })
    }

    fn scan_u_vec(&mut self, n: usize, separator: u8, delimiter: u8) -> Vec<u64> {
        let mut vector = Vec::with_capacity(n);
        if n > 1 {
            for _i in 0..n - 1 {
                vector.push(self.scan_u(separator));
            }
        }
        vector.push(self.scan_u(delimiter));
        vector
    }
}

fn create_cin<'a>(input: StdinLock<'a>, buffer_capacity: usize) -> CharacterInput {
    CharacterInput {
        locked_stdin: input,
        bytes_buffer: Vec::with_capacity(buffer_capacity),
    }
}

// ------------------------------------------------------------------------

fn main() {
    let cin = stdin();
    let cin = &mut create_cin(cin.lock(), 16);

    let n = cin.scan_u(LF) as usize;
    let mut a = cin.scan_u_vec(n + 1, SP, LF);
    let b = cin.scan_u_vec(n, SP, LF);

    let total_count = (0..n).map(|i| {
        let monster_count = a[i] + a[i + 1];
        let max_defeatable_count = b[i];

        if max_defeatable_count >= monster_count {
            a[i + 1] = 0;
            return monster_count;
        }

        if max_defeatable_count > a[i] {
            a[i + 1] = monster_count - max_defeatable_count;
        }

        return max_defeatable_count;
    }).sum::<u64>();

    println!("{}", total_count);
}


use whiteread::parse_line;

fn main() {
    let n: usize = parse_line().unwrap();
    let mut a: Vec<u32> = parse_line().unwrap();
    let mut b: Vec<u32> = parse_line().unwrap();
    let mut cnt = 0;

    for i in 0..n {
        if b[i] < a[i] {
            cnt += b[i];
            b[i] = 0;
        } else {
            cnt += a[i];
            b[i] -= a[i];
        }
        if b[i] < a[i + 1] {
            cnt += b[i];
            a[i + 1] -= b[i];
        } else {
            cnt += a[i + 1];
            a[i + 1] = 0;
        }
    }
    println!("{}", cnt);
}


fn solve() {
    let n = read();
    let mut a: Vec<usize> = vec![];
    for _ in 0..n + 1 {
        a.push(read());
    }
    let mut b: Vec<usize> = vec![];
    for _ in 0..n {
        b.push(read());
    }
    let mut res0 = 0;
    let mut rem = 0;
    for i in 0..n {
        res0 += min(b[i] + rem, a[i]);
        if b[i] + rem > a[i] {
            rem = b[i] - (a[i].saturating_sub(rem));
        } else {
            rem = 0;
        }
    }
    res0 += min(a[n], rem);
    let mut res1 = 0;
    let mut rem = 0;
    for i in (1..n + 1).rev() {
        res1 += min(b[i - 1] + rem, a[i]);
        if b[i - 1] + rem > a[i] {
            rem = b[i - 1] + rem - a[i];
        } else {
            rem = 0;
        }
    }
    res1 += min(a[0], rem);
    println!("{}", res1);
    println!("{}", max(res0, res1));
}

fn main() {
    let stack_size = 104_857_600;
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}

// =========
#[allow(unused_imports)]
use std::cmp::{max, min, Reverse};
#[allow(unused_imports)]
use std::collections::{BinaryHeap, HashMap, HashSet};
#[allow(unused_imports)]
use std::process::exit;

#[allow(dead_code)]
const MOD: usize = 1000000007;

fn read<T: std::str::FromStr>() -> T {
    use std::io::Read;
    let stdin = std::io::stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

// =========


fn solve() {
    let n = read();
    let mut a: Vec<usize> = vec![];
    for _ in 0..n + 1 {
        a.push(read());
    }
    let mut b: Vec<usize> = vec![];
    for _ in 0..n {
        b.push(read());
    }
    let mut res = 0;
    let mut rem = 0;
    for i in 0..n {
        res += min(b[i] + rem, a[i]);
        if b[i] + rem > a[i] {
            rem = b[i] - (a[i].saturating_sub(rem));
        }
    }
    println!("{}", res + min(a[n], rem));
}

fn main() {
    let stack_size = 104_857_600;
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}

// =========
#[allow(unused_imports)]
use std::cmp::{max, min, Reverse};
#[allow(unused_imports)]
use std::collections::{BinaryHeap, HashMap, HashSet};
#[allow(unused_imports)]
use std::process::exit;

#[allow(dead_code)]
const MOD: usize = 1000000007;

fn read<T: std::str::FromStr>() -> T {
    use std::io::Read;
    let stdin = std::io::stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

// =========


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }

    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = index(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt

    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2

        if Int(ary[mid])! < key {
            left = mid

        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }

    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    var monsters = readInts()
    var heroes = readInts()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力

    var ans = 0
    for i in 0..<n{
        ans             += min(heroes[i], monsters[i])
        heroes[i]       -= min(heroes[i], monsters[i])
        monsters[i]     -= min(heroes[i], monsters[i])
        ans             += min(heroes[i], monsters[i + 1])
        monsters[i + 1] -= min(heroes[i], monsters[i + 1])
    }
    print(ans)
}
main()


let N = Int(readLine()!)!
var A = readLine()!.characters.split(" ").map{Int(String($0))!}
let B = readLine()!.characters.split(" ").map{Int(String($0))!}
var ans = 0
for i in 0..<N {
    let a = min(A[i], B[i])
    let b = min(A[i+1], B[i]-a)
    A[i+1] -= b
    ans += a+b
}
print(ans)


let N = Int(readLine()!)!
var A = readLine()!.characters.split(" ").map{Int(String($0))!}
let B = readLine()!.characters.split(" ").map{Int(String($0))!}
var ans = 0
for i in 0..<N {
  ans += min(min(A[i],B[i])+A[i+1],B[i])
  A[i+1] -= min(A[i+1],B[i]-min(A[i],B[i]))
}
print(ans)


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

// https://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }

    return divisors
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {

    mutating func remove(_ element: Element) {
        _ = index(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt

    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2

        if Int(ary[mid])! < key {
            left = mid

        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }

    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    var monsters = readInts()
    var heroes = readInts()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力

    var ans = 0
    for i in 0..<n{
        if heroes[i] >= monsters[i] && monsters[i] > 0{
            ans += monsters[i]
            heroes[i] -= monsters[i]
            ans += min(heroes[i], monsters[i + 1])
            monsters[i + 1] -= heroes[i]

        } else {
            ans += heroes[i]
        }
    }
    print(ans)
}
main()


let N = Int(readLine()!)!
var A = readLine()!.characters.split(" ").map{Int(String($0))!}
let B = readLine()!.characters.split(" ").map{Int(String($0))!}
var ans = 0
for i in 0..<N {
    ans += min(min(A[i],B[i])+A[i+1],B[i])
    A[i]-=min(A[i],B[i])
}
print(ans)


let N=Int(readLine()!)!,A=readLine()!.characters.split(" ").map{Int(String($0))!},B=readLine()!.characters.split(" ").map{Int(String($0))!}
print((0..<N).reduce(0){$0+min(min(A[$1],B[$1])+A[$1+1],B[$1])})


export class Main {
  static main(input): string {
    const tmp: string[] = input.split("\n");
    const n: number = parseInt(tmp[0].split(" ")[0]);
    const a: number[] = tmp[1].split(" ").slice(0, n + 1).map(int => parseInt(int));
    const b: number[] = tmp[2].split(" ").slice(0, n).map(int => parseInt(int));
    let result: number = 0;
    let remain: number = 0;
    for (let i = 0; i < n; i++) {
      if (a[i] <= remain + b[i]) {
        result += a[i];
        remain = b[i] - (Math.max(a[i] - remain, 0));
      } else {
        result += b[i] + remain;
        remain = 0;
      }
    }
    if (a[n] <= remain) {
      result += a[n];
    } else {
      result += remain;
    }
    return `${result}`;
  }
}
 console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));


function main(input) {
  input = input.trim().split("\n");
  const n = Number(input[0]);
  const as = input[1].split(" ").map(n => Number(n));
  const bs = input[2].split(" ").map(n => Number(n));
  let result = 0;
  for(let i = 0; i < n; i++) {
    const a = as[i];
    const nextA = as[i+1];
    const b = bs[i];
    if (b <= a) {
      result += b;
      continue;
    }
    result += a;
    const remainedB = b - a;
    if (remainedB <= nextA) {
      as[i+1] -= remainedB;
      result += remainedB;
      continue;
    }
    result += nextA;
    as[i+1] = 0;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


class NormalInput{
  input: string[];
  pointer: number;
  constructor(raw:string){
    this.input=raw.split(/ |\n/);
    this.pointer=0;
  }
  int():number{
    const ret= parseInt(this.input[this.pointer], 10);
    this.pointer++;
    return ret;
  }
  ints(length:number):number[]{
    let ret:number[]=[];
    for(let i=0;i<length;i++){
      ret.push(this.int());
    }
    return ret;
  }
  str():string{
    const ret= this.input[this.pointer];
    this.pointer++;
    return ret;
  }
  strs(length:number):string[]{
    let ret:string[]=[];
    for(let i=0;i<length;i++){
      ret.push(this.str());
    }
    return ret;
  }
}
function Main(_:NormalInput) {
  const N=_.int();
  const A=_.ints(N+1);
  const B=_.ints(N);
  let count=0;
  for(let i=0;i<N;i++){
    const v=Math.min(A[i],B[i]);
    B[i]-=v;
    count+=v;

    const v2=Math.min(A[i+1],B[i]);
    A[i+1]-=v2;
    count+=v2;
  }
  console.log(count);
}

//DO NOT EDIT
Main(new NormalInput(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'
const main = (input: string) => {
    const std: string[] = input.trim().split('\n')
    const n: number = Number(std.shift())
    const a: number[] = std.shift().split(' ').map(Number)
    const b: number[] = std.shift().split(' ').map(Number)
    let r = 0;
    for (let i = 0; i <= n; i++) {
        const current = Math.min(a[i], b[i])
		r += current
		a[i] -= current
		b[i] -= current
		const next = Math.min(a[i + 1], b[i])
		r += next
		a[i + 1] -= next
		b[i] -= next
    }
    console.log(r);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict'
const main = (input: string) => {
    const std: string[] = input.trim().split('\n')
    const n: number = Number(std.shift())
    const a: number[] = std.shift().split(' ').map(Number)
    const b: number[] = std.shift().split(' ').map(Number)
    const beforeA = Array.from(a)
    let bi = 0
    for (let i = 0; i <= n; i++) {
        while (a[i] !== 0) {
            if (b[bi] === 0 || (b[bi] === 0 && bi === i-1)) {
                bi++
            }
            if (bi === n || ( bi > i)) {
                break
            }
            a[i]--
            b[bi]--
        }
    }
    console.log(sum(beforeA) - sum(a));
}

const sum = (arr: number[]) => {
    let sum = 0
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i]
    }
    return sum
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict'
const main = (input: string) => {
    const std: string[] = input.trim().split('\n')
    const n: number = Number(std.shift())
    const a: number[] = std.shift().split(' ').map(Number)
    const b: number[] = std.shift().split(' ').map(Number)
    const beforeA = Array.from(a)
    let bi = 0
    for (let i = 0; i <= n; i++) {
        while (a[i] !== 0) {
            if (b[bi] === 0 || (b[bi] === 0 && bi === i-1)) {
                bi++
            }
            if (bi === n || ( bi > i)) {
                break
            }
            a[i]--
            b[bi]--
        }
    }
    console.log(sum(beforeA) - sum(a));
}

const sum = (arr: number[]) => {
    return arr.reduce((acc, current) => acc + current)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


w, h, n = map(int, input().split())
b = 0
l = 0

for i in range(n):
    x, y, a = map(int, input().split())
    if a == 1:
        l = max(l, x)
    elif a == 2:
        w = min(w, x)
    elif a == 3:
        b = max(b, y)
    else:
        h = min(h, y)

print(max(h - b, 0)*max(w - l, 0))


w, h, n = list(map(int, input().split()))
x_min, x_max, y_min, y_max = 0, w, 0, h
for _ in range(n):
    x, y, a = list(map(int, input().split()))
    if a == 1:
        x_min = max(x_min, x)
    elif a == 2:
        x_max = min(x_max, x)
    elif a == 3:
        y_min = max(y_min, y)
    else:
        y_max = min(y_max, y)
if x_min >= x_max or y_min >= y_max:
    print(0)
else:
    print((x_max - x_min) * (y_max - y_min))


w,h,n = list(map(int, input().split()))
data = [list(map(int, input().split())) for _ in range(n)]
x1 = y1 = 0
x2,y2 = w,h
for x,y,a in data:
    if a==1:
        x1=max(x1, x)
    elif a==2:
        x2=min(x2, x)
    elif a==3:
        y1=max(y1, y)
    else:
        y2=min(y2, y)
print(max(x2-x1,0)*max(y2-y1,0))


from collections import deque,defaultdict,Counter
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from bisect import bisect_left,bisect_right
from math import sqrt,gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode
import sys
sys.setrecursionlimit(10 ** 6)

INF = float('inf')
mod = 10**9 + 7

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse=False):
    data.sort(key=lambda x:x[col],reverse=revese)
    return data

def mymax(data):
    M = -1*float('inf')
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float('inf')
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def mydictvaluesort(dictionary):
    return sorted( dictionary.items(), key=lambda x:x[1] )

def mydictkeysort(dictionary):
    return sorted( dictionary.items(), key=lambda x:x[0] )

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(' ')
        elif type(ls[0])==str:
            print(' '.join(ls))
        elif type(ls[0])==int:
            print(' '.join(map(str,ls)))
        else:
            print('Output Error')
    else:
        if len(ls)==0:
            print('')
        elif type(ls[0])==str:
            print(''.join(ls))
        elif type(ls[0])==int:
            print(''.join(map(str,ls)))
        else:
            print('Output Error')

def I():
    return int(input())

def MI():
    return map(int,input().split())

def RI():
    return list(map(int,input().split()))

def CI(n):
    return [ int(input()) for _ in range(n) ]

def LI(n):
    return [ list(map(int,input().split())) for _ in range(n) ]

def S():
    return input()

def MS():
    return input().split()

def RS():
    return list(input())

def CS(n):
    return [ input() for _ in range(n) ]

def LS(n):
    return [ list(input()) for _ in range(n) ]

# ddict = defaultdict(lambda: 0)
# ddict = defaultdict(lambda: 1)
# ddict = defaultdict(lambda: int())
# ddict = defaultdict(lambda: list())
# ddict = defaultdict(lambda: float())

w,h,n = MI()
xya = LI(n)

xs,xe = 0,w
ys,ye = 0,h

for i in xya:
    x,y,a = i
    if a==1:
        xs = max(xs,x)
    elif a==2:
        xe = min(xe,x)
    elif a==3:
        ys = max(ys,y)
    elif a==4:
        ye = min(ye,y)

s = abs(xe-xs)*abs(ye-ys)
if s<0:
    print(0)
else:
    print(s)


from collections import deque,defaultdict,Counter
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from bisect import bisect_left,bisect_right
from math import sqrt,gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode
import sys
sys.setrecursionlimit(10 ** 6)

INF = float('inf')
mod = 10**9 + 7

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse=False):
    data.sort(key=lambda x:x[col],reverse=revese)
    return data

def mymax(data):
    M = -1*float('inf')
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float('inf')
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def mydictvaluesort(dictionary):
    return sorted( dictionary.items(), key=lambda x:x[1] )

def mydictkeysort(dictionary):
    return sorted( dictionary.items(), key=lambda x:x[0] )

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(' ')
        elif type(ls[0])==str:
            print(' '.join(ls))
        elif type(ls[0])==int:
            print(' '.join(map(str,ls)))
        else:
            print('Output Error')
    else:
        if len(ls)==0:
            print('')
        elif type(ls[0])==str:
            print(''.join(ls))
        elif type(ls[0])==int:
            print(''.join(map(str,ls)))
        else:
            print('Output Error')

def I():
    return int(input())

def MI():
    return map(int,input().split())

def RI():
    return list(map(int,input().split()))

def CI(n):
    return [ int(input()) for _ in range(n) ]

def LI(n):
    return [ list(map(int,input().split())) for _ in range(n) ]

def S():
    return input()

def MS():
    return input().split()

def RS():
    return list(input())

def CS(n):
    return [ input() for _ in range(n) ]

def LS(n):
    return [ list(input()) for _ in range(n) ]

# ddict = defaultdict(lambda: 0)
# ddict = defaultdict(lambda: 1)
# ddict = defaultdict(lambda: int())
# ddict = defaultdict(lambda: list())
# ddict = defaultdict(lambda: float())

w,h,n = MI()
xya = LI(n)

xs,xe = 0,w
ys,ye = 0,h

for i in xya:
    x,y,a = i
    if a==1:
        xs = max(xs,x)
    elif a==2:
        xe = min(xe,x)
    elif a==3:
        ys = max(ys,y)
    elif a==4:
        ye = min(ye,y)

s = (xe-xs)*(ye-ys)
if s<0:
    print(0)
else:
    print(s)


from collections import deque,defaultdict,Counter
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from bisect import bisect_left,bisect_right
from math import sqrt,gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode
import sys
sys.setrecursionlimit(10 ** 6)

INF = float('inf')
mod = 10**9 + 7

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse=False):
    data.sort(key=lambda x:x[col],reverse=revese)
    return data

def mymax(data):
    M = -1*float('inf')
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float('inf')
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def mydictvaluesort(dictionary):
    return sorted( dictionary.items(), key=lambda x:x[1] )

def mydictkeysort(dictionary):
    return sorted( dictionary.items(), key=lambda x:x[0] )

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(' ')
        elif type(ls[0])==str:
            print(' '.join(ls))
        elif type(ls[0])==int:
            print(' '.join(map(str,ls)))
        else:
            print('Output Error')
    else:
        if len(ls)==0:
            print('')
        elif type(ls[0])==str:
            print(''.join(ls))
        elif type(ls[0])==int:
            print(''.join(map(str,ls)))
        else:
            print('Output Error')

def I():
    return int(input())

def MI():
    return map(int,input().split())

def RI():
    return list(map(int,input().split()))

def CI(n):
    return [ int(input()) for _ in range(n) ]

def LI(n):
    return [ list(map(int,input().split())) for _ in range(n) ]

def S():
    return input()

def MS():
    return input().split()

def RS():
    return list(input())

def CS(n):
    return [ input() for _ in range(n) ]

def LS(n):
    return [ list(input()) for _ in range(n) ]

# ddict = defaultdict(lambda: 0)
# ddict = defaultdict(lambda: 1)
# ddict = defaultdict(lambda: int())
# ddict = defaultdict(lambda: list())
# ddict = defaultdict(lambda: float())

w,h,n = MI()
xya = LI(n)

xs,xe = 0,w
ys,ye = 0,h

for i in xya:
    x,y,a = i
    if a==1:
        xs = x
    elif a==2:
        xe = x
    elif a==3:
        ys = y
    elif a==4:
        ye = y
    else:
        print('E')

s = (xe-xs)*(ye-ys)
if s<0:
    print(0)
else:
    print(s)