jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
x = gets.chomp.to_i
list = (1..4999).to_a
list.map! {|i| i*2+1}
prime_list = [2]
while true
    value = list[0]
    prime_list.push(value)
    list.delete_if{|num| num % value == 0}
    if list.size == 0
        break
    end
end
prime_list.push(100003)
first = prime_list.index {|v| v >= x }
print prime_list[first]
//  [ruby]
x = gets.chomp.to_i
list = (2..100000).to_a
prime_list = []
sqrt = Math.sqrt(x).floor
while true
    value = list[0]
    prime_list.push(value)
    list.delete_if{|num| num % value == 0}
    if list.size == 0
        break
    end
end
prime_list.push(100003)
first = prime_list.index {|v| v > x }
print prime_list[first]
//  [rust]
fn main() {
    let n = read::<u32>();

    let mut x = n;
    loop {
        if is_prime(x) {
            println!("{}", x);
            break;
        }
        x += 1
    }
}

fn is_prime(n: u32) -> bool {
    n != 1 && (2..).take_while(|x| x * x <= n).all(|x| n % x != 0)
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().parse().ok().unwrap()
}
//  [rust]
use proconio::{fastout, input};

#[fastout]
fn main() {
    // input! {n: usize, ab: [[usize;2];n]};
    // let mut ab: Vec<Vec<usize>> = ab;

    input! {x: usize};

    let mut b = true;
    if x <= 2 {
        println!("2")
    }
    let mut i = x;
    while true {
        let mut j = 3;
        while j <= (i as f64).sqrt() as usize {
            if i % j == 0 {
                b = false;
                break;
            }
            j += 2;
        }
        if b {
            println!("{}", i);
            break;
        }
        i += 2;
    }
}
//  [rust]
use std::io::*;
use std::str::FromStr;
use std::collections::*;

fn read<T: FromStr>() -> T {
    let stdin = 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 get_next_prime(mut x: usize) {
    loop {
        let mut is_prime_cnt = 0;
        for p in 2..x {
            if x%p==0 {
                break;
            } else {
                is_prime_cnt += 1;
            }
        }
        if is_prime_cnt==x-2 {
            println!("{}", x);
            return;
        }
    }
    x += 1;
}


fn main() {
    let X: usize = read();
    get_next_prime(X);
}
//  [rust]
use std::io::*;
use std::str::FromStr;
use std::collections::*;

fn read<T: FromStr>() -> T {
    let stdin = 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 get_next_prime(mut x: usize) {
    loop {
        x += 1;
        let mut is_prime_cnt = 0;
        for p in 2..x {
            if x%p==0 {
                break;
            } else {
                is_prime_cnt += 1;
            }
        }
        if is_prime_cnt==x-2 {
            println!("{}", x);
            return;
        }
    }
}


fn main() {
    let X: usize = read();
    get_next_prime(X);
}
//  [swift]
func is_prime(n: Int) -> Bool{
    if (n <= 1) {
        return false
    }

    if (n <= 3) {
        return true
    }

    var i = 2
    while (i*i <= n) {
        if (n % i == 0) {
           return false
        }
      
        i = i + 1
    }
    return true
}

let a=Int(readLine()!)!

var i = 0
while( true ) {
	if( is_prime(a + i) ) {
      print(a + i)
      break
    }
    i += 1
}
//  [swift]
// 🐋💭 Next Prime
import Foundation

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

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



func main() {
    var x = readInt()
    var count = 0
    var isNotPrime = true
    
    while isNotPrime {
        for i in 1..<x {
            count += x % i == 0 ? 1: 0
            if count > 1 {
                break
            }
            
        }
        if count > 1 {
            count = 0
            x += 1
        } else {
            isNotPrime = false
        }
        
    }
    print(x)
}
main()
//  [swift]
import Foundation
// 第一引数に、素数かどうかを判定したい自然数を渡す
func check_primes(n:Int)->Bool{
    // 計算するのは√nまでで十分
    for i in 2...Int(sqrt(Double(n)))+1{
        // コーナーケースになりうるものは除いておく
        if i > n || n == 2{
            continue
        }
        if n%i == 0{
            return false
        }
    }
    return true
}

// 標準入力の受け取り
var x = Int(readLine()!)!

// 素数に当たるまでループを回す
while !check_primes(n:x){
    x+=1
}

// 答えを出力
print(x)
//  [swift]
import Foundation
// 第一引数に、素数かどうかを判定したい自然数を渡す
func check_primes(n:Int)->Bool{
    // 計算するのは√nまでで十分
    for i in 2...Int(sqrt(Double(n))){
        if n%i == 0{
            return false
        }
    }
    return true
}

// 標準入力の受け取り
var x = Int(readLine()!)!

// 素数に当たるまでループを回す
while !check_primes(n:x){
    x+=1
}

// 答えを出力
print(x)
//  [typescript]
const main = (input: string) => {
  const N = parseInt(input.trim())
  let isNotFound = true
  let primeNumber = N

  const getPrimeNumber = (n: number) => {
    if (n === 2) return true;
    for (let i = 2; i < n; i++) {
      if (n % i === 0) return false;
    }
    return true;
  }

  let count = 0
  while(isNotFound) {
    if(getPrimeNumber(N + count)) {
      primeNumber = N + count
      isNotFound = false
    }
    count += 1
  }
  console.log(primeNumber)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const [x]: number[] = tmp[0].split(" ").map(int => parseInt(int));
    let result = x;
    while(true) {
      if (Main.isPrime(result)) {
        return `${result}`;
      }
      result++;
    }
  }
  static isPrime(x) {
    for (let i = 2, len = Math.floor(Math.sqrt(x)); i <= len; i++) {
      if (x % i == 0) {
        return false;
      }
    }
    return true;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
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){
    if(isPrime(a)){
      to(a)
      return
    }
    a++
  }
}
main()
//  [typescript]
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()
//  [typescript]
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'))
//  [python]
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()
//  [python]
#!/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()
//  [python]
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()
//  [python]
#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()
//  [python]
#-*-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()
//  [python]
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)
//  [java]
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);

	}
}
//  [java]
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);
    }
}
//  [cpp]
#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);
}
//  [cpp]
#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);
}
//  [cpp]
#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;
}
//  [cpp]
#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;
}
//  [cpp]
#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;
}
//  [cpp]
#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;
}
//  [c]
// 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;
}
//  [c]
#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;
}
//  [c]
#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;
}
//  [c]
#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);
}
//  [c]
#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;
}
//  [c]

#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;
}
//  [javascript]
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"));
//  [javascript]
// 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"));
//  [javascript]
// 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"));
//  [javascript]
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"));
//  [javascript]
//↓見なくていいよ！ここから--------------------------------------------------
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);
}
//  [javascript]
//↓見なくていいよ！ここから--------------------------------------------------
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);
}
//  [go]
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)
}
//  [go]
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()
}
//  [go]
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)
}
//  [go]
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)
}
//  [go]
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)
}
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [ruby]
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
//  [rust]
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);
}
//  [rust]
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);
}