jiahuimbzuai/CoQuIR huggingface dataset:
//  [c]
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define GYOU_MAX 256

int main(void) {
	int X;
	scanf("%d", &X);
	int flag;
	for (int i = 2; ; i++) {
		flag = 0;
		for (int j = 2; j <i; j++) {
			if (i%j == 0) {
				flag = 1;
				break;
			}
		}
		if (flag == 0 && i >= X) {
			printf("%d", i);
			break;
		}
	}

	return 0;


}
//  [javascript]
function Main (N) {
  N = parseInt(N.split("\n")[0], 10);
  while (true) {
    if (primeNumber(N)) {
      console.log(N);
      break;
    }
    else {
      N++;
    }
  }
}
function primeNumber (num) {

    //2 は素数なので true を返す
    if(num === 2) {
        return true;
    } else {

        for(i = 2; i < num; i++) {

        //2以上の数で割ったとき余りが0になれば false を返す。つまり素数ではない。
            if(num % i === 0) {
                return false;
                break;
            }

            //ループが最後まで行く、つまり割れる数がなかったら true を返す。つまり素数。
            if(i + 1 === num) {
                return true;
            }
        }
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function main(input) {
  var primes = [2, 3]
  if (input == 2 || input == 3) {
    return console.log(input);
  }

  var base = 6
  while (true) {
    var root = Math.ceil(Math.sqrt(base))
    var tests = primes.filter(p => p <= root)

    var elder = base - 1
    var younger = base + 1

    if (tests.every(p => elder % p != 0)) {
      primes.push(elder);
      if (input <= elder) {
        return console.log(elder);
      }
    }
    if (tests.every(p => younger % p != 0)) {
      primes.push(younger);
      if (input <= younger) {
        return console.log(younger);
      }
    }
    base = base + 6;
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function Main(input) {
	var tmp = input.split("\n");
	var a = Number.parseInt(tmp);
  var b = findPrime(a);
	console.log('%s', b);
}

function findPrime(x) {
  for (var i = x;; i++) {
    if (isPrime(i)) {
      return i;
    }
  }
}

function isPrime(x) {
  for (var i = 2; i < x; i++) {
    if (x % i === 0) {
      return false;
    }
  }
  return true;
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import "fmt"

func main() {
	var x int
	fmt.Scan(&x)
	for _, n := range sosuu() {
		if n >= x {
			fmt.Println(n)
			return
		}
	}
}

func sosuu() []int {
	sosuus := []int{2}
outer:
	for i := 3; i < 200000; i++ {
		for n := 0; n < len(sosuus); n++ {
			if i%sosuus[n] == 0 {
				continue outer
			}
		}
		sosuus = append(sosuus, i)
	}
	return sosuus
}
//  [go]
package main

import (
	"fmt"
	"math"
)

const n = 100003

func min(x, y int) int {
	if x <= y {
		return x
	}
	return y
}

func findMin(nums []int) int {
	m := n
	for _, v := range nums {
		if v < m {
			m = v
		}
	}
	return m
}

func findPrime(x int) int {
	nums := make([]int, n)
	for i := 0; i < n; i++ {
		nums[i] = i + 2
	}

	primes := make([]int, 0)
	for true {
		p := findMin(nums)

		if p >= x {
			return p
		}
		if p > int(math.Sqrt(n)) {
			break
		}
		primes = append(primes, p)
		i := 0
		for i < len(nums) {
			if nums[i]%p == 0 {
				nums = append(nums[:i], nums[i+1:]...)
				continue
			}
			i++
		}
	}
	for _, v := range nums {
		primes = append(primes, v)
	}
	for _, v := range primes {
		if v >= x {
			return v
		}
	}
	return -1
}

func main() {
	var x int
	fmt.Scan(&x)

	fmt.Println(findPrime(x))
}
//  [go]
package main

import "fmt"

func main() {
	var x int
	fmt.Scan(&x)

	if x <= 2 {
		fmt.Println("2")
		return
	}

	sosu := []int{2}

	for i := 3; ; i++ {
		isSosu := true
		for _, v := range sosu {
			if i%v == 0 {
				isSosu = false
				break
			}
		}
		if isSosu {
			sosu = append(sosu, i)
			if i >= x {
				break
			}
		}
	}
	fmt.Println(sosu[len(sosu)-1])
}
//  [ruby]
n = STDIN.gets.chomp.to_i

prime = []
# ルート 100000まででOK
max =  Math.sqrt(100000).round
[*(2..100003)].each do |x|
  p_flg = true
  prime.each do |y|
    if x % y == 0
      p_flg = false
    end
    if y >= max
      break
    end
  end
  if p_flg
    if x >= n
      puts x
      break
    end
    prime.push(x)
  end
end
//  [ruby]
require 'prime'

x = gets.to_i
number = *1..1000000

number.map do |n|
  if Prime.prime?(n) && n >= x
    puts n
    break
  end
end
//  [ruby]
X = gets.to_i
l = [*2..100003]
t = Math.sqrt(100003)
(2..t.ceil).each{|i|
  l.reject! {|item| item % i == 0 && item != i}  
}
l.each{|i|
  if X <= i
    puts i
    exit
  end
}
//  [rust]
// input! macro is published in the following URLs.
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
// https://github.com/tanakh/competitive-rs.git
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

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

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, [ $t:tt ]) => {
        {
            let len = read_value!($next, usize);
            (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
        }
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        x: usize
    }
    fn is_prime(x: usize, primes: &mut Vec<usize>) -> bool {
        for prime in primes.iter() {
            if x % *prime == 0 {
                return false;
            }
        }
        primes.push(x);
        true
    }
    let mut primes = vec![];
    for i in 2..x {
        is_prime(i, &mut primes);
    }
    for i in x.. {
        if is_prime(i, &mut primes) {
            println!("{}", i);
            return;
        }
    }
}
//  [rust]
fn main() {
    let num: i32 = read();
    if num == 2 {
        println!("{}", num);
        return;
    }

    let mut prime = vec![2];

    let mut i = 1;
    'outer: loop {
        i += 2;
        for n in prime.iter() {
            if i % n == 0 {
                continue 'outer;
            }
        }

        prime.push(i);

        if num <= *prime.last().unwrap() {
            break;
        }
    }

    println!("{}", i)
}

#[allow(dead_code)]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

#[allow(dead_code)]
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}
//  [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) {
    console.log(result)
    return
  }
  if (result%2 === 0) result++
  while(true) {
  	if (isPrime(result)) break;
  	result += 2
  }
  console.log(result)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [typescript]
function Main(input) {
	const lines = input.split("\n");
  let x = lines[0] * 1;

  while (true) {
    let flag = 0;
    for (let i = 2; i < x; i++) {
      if (x % i == 0) {
        flag = 1;
        break;
      }
    }
    if (!flag) break;
    x++;
  }
	console.log(x);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
{
  const main = (input: string): void | string | number => {
    const r = _reader(input)
    const X = r.n()

    for (let i = X; i < X + 10000; i++) {
      if (_isPrime(i)) {
        return i
      }
    }

    return -1
  }

  const _reader = (str: string, i = 0) => {
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')
    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map(v => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }
  const _isPrime = (n: number) => {
    for (var i = 2; i < n; i++) if (n % i === 0) return false
    return n > 1
  }

  const _getInput = () => require('fs').readFileSync('/dev/stdin', 'utf8')
  const _res = main(_getInput())

  if (typeof _res === 'number' || typeof _res === 'string') console.log(_res)
}
//  [python]
import numpy as np
N = int(input())
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]

count = 0
for i in range(N):
    if B[i] <= A[i]:
        count += B[i]
    else:
        count += A[i] + np.minimum((B[i] - A[i]), A[i+1])
        A[i+1] -= np.minimum((B[i] - A[i]), A[i+1])
print(count)
//  [python]
import numpy as np
n = int(input())
a = np.array(list(map(int, input().split())))
c = a.copy()
b = list(map(int, input().split()))
for i in range(n):
    for j in range(2):
        if a[i+j] <= b[i]:
            b[i] -= a[i+j]
            a[i+j] = 0
        else:
            a[i+j] -= b[i]
            b[i] = 0
print(sum(c-a))
//  [python]
import numpy as np
N = int(input())
A = [int(i) for i in input().split()] 
B = [int(i) for i in input().split()] 
C = np.zeros(N+1)
count = 0
for i in range(N):
  a = A[i] - B[i] -C[i]
  if a >= 0:
    count += B[i] + C[i]
  else:
    count += A[i]
    if A[i] - C[i] < 0:
      C[i+1] = B[i]
    else:
      C[i+1] = -a
if C[N] > 0:
  if A[N] < C[N]:
    count += A[N]
  else:
    count += C[N]
print(int(count))
//  [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];

    long res = 0;

    for (int i = 0; i <= n; i++)
      a[i] = sc.nextLong();
    for (int i = 0; i < n; i++) {
      b[i] = sc.nextLong();
      if (b[i] > a[i]) {
        res += a[i];
        long carry = Math.min(a[i + 1], b[i] - a[i]);
        a[i + 1] -= carry;
        res += carry;
      } else
        res += b[i];
    }

    System.out.println(res);
  }
}
//  [java]
import java.util.*;
import java.io.*;
//https://atcoder.jp/contests/abc135/tasks/abc135_c
//city savers
class Main
{
	public static void main(String args[])throws IOException
	{
		double n,max=0,i;
		Scanner sc=new Scanner(System.in);
		n=sc.nextDouble();
		double a[]=new double[(int)n+1];
		double b[]=new double[(int)n];
		for( i=0;i<n+1;i++)
		{
			a[(int)i]=sc.nextDouble();
		}

		for( i=0;i<n;i++)
			b[(int)i]=sc.nextDouble();
		for( i=n-1;i>=0;i--)
		{
			if(b[(int)i]<=a[(int)i+1])
			{
				max+=b[(int)i];
				a[(int)i+1]-=b[(int)i];
				b[(int)i]=0;

				
			}
			else if(b[(int)i]>a[(int)i+1])
			{
				max+=a[(int)i+1];
				b[(int)i]-=a[(int)i+1];
				a[(int)i+1]=0;
				if(b[(int)i]<=a[(int)i])
				{
					max+=b[(int)i];
					a[(int)i]-=b[(int)i];
					b[(int)i]=0;
				}
				else if(b[(int)i]>a[(int)i])
				{
					max+=a[(int)i];
					b[(int)i]-=a[(int)i];
					a[(int)i]=0;

				} 	
			}
			
		}
		
		System.out.println((long)max);
	}
}
//  [java]
import java.util.*;

import javax.swing.plaf.synth.SynthSplitPaneUI;

public class Main{
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        List<Integer> A = new ArrayList<>();
        for(int i= 0;i<N+1;i++){
            int a = scanner.nextInt();
            A.add(a);
        }
        List<Integer> B = new ArrayList<>();
        for(int i= 0;i<N;i++){
            int b = scanner.nextInt();
            B.add(b);
        }

        Map<List<Integer>, Integer> x = new HashMap<>();
        for(int i=0; i<N; i++){
            List<Integer> ii = new ArrayList<>(Arrays.asList(i, i));
            List<Integer> iminus1i = new ArrayList<>(Arrays.asList(i-1,i));
            List<Integer> iiplus1 = new ArrayList<>(Arrays.asList(i, i+1));
            if(i==0){
                x.put(ii, Math.min(A.get(i), B.get(i)));
            }else{
                x.put(ii, Math.min(A.get(i) - x.get(iminus1i), B.get(i)));
            }
            x.put(iiplus1, Math.min(B.get(i) - x.get(ii), A.get(i+1)));
        }
        long result = 0;
        for(Integer val: x.values()){
            result += val;
        }
        System.out.println(result);
    }
}
//  [cpp]
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define int long long
#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c> {i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifndef LOCAL
	~debug() { cerr << endl; }
	eni( != ) cerr << boolalpha << i; ris;
}
eni( == ) ris << range(begin(i), end(i));
}
sim, class b dor(pair < b, c > d) {
	ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
	*this << "[";
	for (auto it = d.b; it != d.e; ++it)
		*this << ", " + 2 * (it == d.b) << *it;
	ris << "]";
}
#else
	sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
template <typename T>
using indexed_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define int long long
#define ld long double
#define pb push_back
#define mp make_pair
#define in insert
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define mod 1000000007
#define sz(v) (int)(v.size())
#define all(x) x.begin(), x.end()
#define prec fixed << setprecision(12)
#define rep(i, a, b) for (int i = a; i <= b; ++i)
#define repr(i, a, b) for(int i = a; i >= b; i--)
#define test int t; cin >> t; while(t--)
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef set<int> si;
typedef map<int, int> mii;
typedef vector<pii> vpi;
int _x[] = {0, 0, -1, 1, -1, 1, -1, 1};
int _y[] = { -1, 1, 0, 0, 1, -1, -1, 1};

void solve() {
    int n;
    cin >> n;
    vi a(n+1), b(n);
    rep(i, 0, n) cin >> a[i];
    rep(i, 0, n-1) cin >> b[i];
    int ans = 0;
    rep(i, 0, n-1){
        debug() << imie(a[i]) imie(b[i]) imie(ans);
        if(b[i] >= a[i]){
            ans += a[i];
            b[i]-=a[i];
            a[i] = 0;
        }else{
            ans += b[i];
            a[i]-=b[i];
            b[i] = 0;
        }
        if(b[i] >= a[i+1]){
            ans += a[i+1];
            b[i] -= a[i+1];
            a[i+1] = 0;
        }else{
            ans += b[i];
            a[i+1] -= b[i];
            b[i] = 0;
        }
    }
    cout << ans << "\n";
}

signed main() {
    ios::sync_with_stdio(false); cin.tie(NULL);
	// test
	solve();
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define pb push_back
#define mk make_pair
#define all(c) (c).begin(),(c).end()
#define debug(x) cerr<<#x<<" = "<<x<<endl;
#define debug2(x,y) cerr<<"("<<#x<<","<<#y<<") = ("<<x<<","<<y<<")\n";
#define debugM(x,n,m) rep(i,0,n){ rep(j,0,m) cerr<<x[i][j]<<" ";cerr<<endl;}
#define debugV(x,n) rep(i,0,n){cerr<<x[i]<<" ";}cerr<<endl; 
#define pi 3.14159265358979323846264338
typedef pair<int,int> ii;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-9;
const int MOD = 1e9+7;
   
ll n,h[100100],m[100100];
int main(){
	
	cin>>n;
	rep(i,0,n+1){
		cin>>m[i];
	}
	rep(i,0,n){
		cin>>h[i];
	}
	
	ll ans=0;
	rep(i,0,n){
		debug(i)
		cerr<<"Before: ";
		debug2(m[i],h[i])
		if(m[i]>0){
			ll aux=min(h[i],m[i]);
			h[i]-=aux;
			ans+=aux;
			m[i]-=aux;
			
		}
		ll aux=min(h[i],m[i+1]);
		h[i]-=aux;
		ans+=aux;
		m[i+1]-=aux;
			
		
		cerr<<"After: ";
		debug2(m[i],h[i])
		debug(ans)
		cerr<<endl;
	}
	
	cout << ans<<endl;
}
//  [cpp]
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <string>
#include <set>
#define INF 1000000000
#define LLINF 2000000000000000
using namespace std;
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define LOOP(i,N) for(int i=0;i<N;i++)
#define LOOP1(i,N) for(int i=1;i<=N;i++)
typedef pair<int,int> P;
typedef pair<int,pair<int,int> > PP;
#define int long long

signed main(){
	int n;
	cin >> n;
	int a[n+1];
	LOOP(i,n+1) cin >> a[i];
	int b[n];
	LOOP(i,n) cin >> b[i];

	int leftsum = 0;
	int lscore = 0;
	int lmp = 0;
	LOOP(i,n){
		lscore = min(b[i],(a[i]-lmp)<0 ? 0 : a[i]-lmp);
		leftsum += lscore;
		lmp = b[i]-lscore;
		leftsum += min(lmp,a[i+1]);
		cerr << lscore << ":" << lmp << endl;
	}
	int ra[n+1];
	int rb[n+1];
	int rsum = 0;
	int rscore = 0;
	int rmp = 0;
	LOOP(i,n+1){
		ra[i]=a[n-i];
		cerr << ra[i] << ",";
	}cerr << endl;
	LOOP(i,n){
		rb[i]=b[n-i-1];
		cerr << rb[i] << ",";
	}cerr << endl;

	LOOP(i,n){
		rscore = min(rb[i],(ra[i]-rmp)<0 ? 0 : ra[i]-rmp);
		rsum += rscore; cerr << rsum << "/";
		rmp = rb[i]-rscore; cerr << rmp << "/";
		rsum += min(rmp,ra[i+1]);cerr << rsum << "/";
		cerr << rscore << ":" << rmp << endl;
	}
	cerr << leftsum << "*" << rsum << endl;
	cout << max(leftsum,rsum) << endl;
}
//  [c]
#include<stdio.h>

int main(){

long ans=0;
int N;
scanf("%d",&N);

int A[N+1];
int B[N];

for (int i = 0; i < N+1; i++){scanf("%d",&A[i]);}
for (int i = 0; i < N; i++){scanf("%d",&B[i]);}

for (int i = N; i > 0; i--)
{
  if (B[i-1]-A[i]<=0)
  {
    ans += B[i-1];
  }else{
    ans += A[i];
    B[i-1] = B[i-1] - A[i];
    if (B[i-1]-A[i-1]<=0)
    {
      ans += B[i-1];
      A[i-1] = A[i-1]-B[i-1];
    }else{
      ans += A[i-1];
      A[i-1] = 0;
    } 
  }
}

printf("%ld",ans);

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[0]=0;
  B[N+1]=0LL;
  long long int C=0;
  for(int i=1;i<=N+1;i++){
    S+=A[i]>B[i-1]?B[i-1]:A[i];
    A[i]=A[i]>B[i-1]?A[i]-B[i-1]:0;
    S+=A[i]>B[i]?B[i]:A[i];
    B[i]=A[i]>B[i]?0:B[i]-A[i];
  }
  printf("%lld\n",S);
  return 0;
}
//  [c]
//135_c
#include <stdio.h>

typedef long long ll;
#define rep(i,a,b,c) for(ll i=(a);i<(b);i+=(c))


ll min(ll a, ll b){if(a<b)return a;else return b;}

int main(void){
    ll N,ans=0,power_i,power_j;
    scanf("%lld",&N);
    ll a[N+5],b[N+5];
    rep(i,0,N+1,1){
        scanf("%lld",&a[i]);
    }
    rep(i,0,N,1){
        scanf("%lld",&b[i]);
    }
    power_i=min(a[0],b[0]);
    power_j=min(a[1],b[0]-power_i);
    // printf("%lld %lld\n",power_i,power_j);
    ans=ans+power_i+power_j;
    rep(i,1,N,1){
        power_i=min(a[i]-power_j,b[i]);
        power_j=min(a[i+1],b[i]-power_i);
        ans=ans+power_i+power_j;
        // printf("%lld %lld\n",power_i,power_j);
    }
    printf("%lld\n",ans);
    return 0;
}
//  [javascript]
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

console.log(main());
function main(){
  var n = o.a();
  var a = o.l();
  var b = o.l();
  var ans = 0;
  for(var i = 0; i < n; i++){
    var mn = Math.min(a[i],b[i]);
    ans += mn;
    var y = b[i] - mn;
    if(y){
      mn = Math.min(a[i+1],y);
      ans += mn;
      a[i+1] -= mn;
    }
  }
  return ans;
}
//  [javascript]
function Main(input) {
  var N = parseInt(input.split("\n")[0]);
  var Alist = input.split("\n")[1].split(" ");
  var Blist = input.split("\n")[2].split(" ");
  
  for(var i = 0; i < Alist.length; i++){
    Alist[i] = parseInt(Alist[i]);
    if(i < Blist.length){
       Blist[i] = parseInt(Blist[i]);
    }
  }
  
  var output = 0;
  
  for(var i = 0; i < Blist.length; i++){
    var tmpA1 = Alist[i];
    var tmpA2 = Alist[i + 1];
    var tmpB = Blist[i];
    
    output += Math.min(tmpA1,tmpB);
    tmpB = tmpB - Math.min(tmpA1,tmpB);
    if(tmpB == 0){
       continue;
    }else{
      output += Math.min(tmpA2,tmpB);
      if(tmpA2 - tmpB > 0){
     	Alist[i + 1] = tmpA2 - tmpB;
      }else{
        Alist[i + 1] = 0;
      }
    }
  }
  console.log(output);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)

	a := make([]int , n+1)
	for i := 0 ; i < n +1; i++ {
		fmt.Scan(&a[i])

	}
	b := make([]int , n)
	for i := 0 ; i < n; i++ {
		fmt.Scan(&b[i])
	}
	cnt := 0
	for i := 0; i < n; i++ {
		if a[i] >= b[i] {
			cnt += b[i]
		} else {
			sub := b[i] - a[i]
			cnt += a[i]
			if a[i+1] > sub {
				cnt += sub
				a[i+1] -= sub
			} else {
				cnt += a[i+1]
				a[i+1] = 0
			}
		}
	}
	fmt.Println(cnt)
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	
	 a := make([]int, n+1)
	 b := make([]int, n)
	 
	 for i := range a {
	 	fmt.Scan(&a[i])
	 }
	 
	 for i := range b {
	 	fmt.Scan(&b[i])
	 }
	 
	 ans := 0
	 for i := 0; i < n; i++ {
	 	
	 	t := min(a[i], b[i])
	 	ans += t
	 	b[i] -= t
	 	
	 	t = min(a[i+1], b[i])
	 	a[i+1] -= t
	 	ans += t
	 }
	 fmt.Println(ans)
}

func min(a, b int)int {
	if a < b {
		return a
	}
	return b
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	a := make([]int64, n + 1)
	b := make([]int64, n)
	for i := 0; i < n+1; i++ {
		fmt.Scanf("%d", &a[i])
	}
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &b[i])
	}
	count := int64(0)
	for i := 0; i < n; i++ {
		if a[i] > b[i] {
			count += b[i]
			b[i] = 0
			a[i] -= b[i]
		} else {
			count += a[i]
			b[i] -= a[i]
			a[i] = 0
		}
		if a[i+1] > b[i] {
			count += b[i]
			a[i+1] -= b[i]
		} else {
			count += a[i+1]
			a[i+1] = 0
		}
	}
	fmt.Println(count)
}
//  [ruby]
eval'N,X,*A='+`dd`.split*?,
p A[0,N].sum{X=[X-t=[X+_1,A[~N-=1]].min,0].min+_1
t}
//  [ruby]
eval"N,X,*A="+`dd`.split*?,
s=0
A.pop(N).zip(A){|b,a|s+=t=[X+=a,b].min
X=[X-t,a].min}
p s
//  [ruby]
eval"N,X,*A="+`dd`.split*?,
s=0
A.pop(N).zip(A).map{|b,a|s+=t=[X+=a,b].min
X=[X-t,a].min}
p s
//  [rust]
use text_io::*;
use std::collections::*;
use std::process::exit;
use std::cmp::max;
use std::fs::read;

fn main() {
    let mut n:usize = read!();
    let mut va:Vec<usize> = Vec::new();
    let mut vb:Vec<usize> = Vec::new();
    for i in 0..n+1 {
        let mut a:usize = read!();
        va.push(a);
    }
    let mut sum:usize = 0;
    for i in 0..n {
        let mut a:usize = read!();
        if va[i]<=a {
            sum+=va[i];
            if va[i+1]+va[i]<a {
                sum+=va[i+1];
                va[i+1]=0;
            }
            else {
                va[i+1]=va[i+1]+va[i]-a;
                sum+=a-va[i];
            }
        }
        else {
            sum+=a;
        }
    }
    println!("{}",sum);
}
//  [rust]
use std::io::*;
use std::str::FromStr;

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 read_n<T: FromStr>(n: usize) -> Vec<T> {
  read_n_logic::<T>(n, vec![])
}

fn read_n_logic<T: FromStr>(n: usize, mut a: Vec<T>) -> Vec<T> {
  match n {
    0 => a,
    _ => {
      a.push(read::<T>());
      read_n_logic(n - 1, a)
    }
  }
}

fn main() {
  let n = read::<usize>();
  let mut a = read_n::<usize>(n + 1);
  let mut b = read_n::<usize>(n);
  let mut answer = 0;

  a.reverse();
  b.reverse();

  for i in 0..b.len() {
    for add in 0..2 {
      if b[i] > a[i + add] {
        answer += a[i + add];
        b[i] -= a[i + add];
        a[i + add] = 0;
      } else {
        answer += b[i];
        a[i + add] -= b[i];
        b[i] = 0;
      }
    }
  }

  println!("{}", answer);
}
//  [rust]
use std::io::*;
use std::str::FromStr;

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 read_n<T: FromStr>(n: usize) -> Vec<T> {
  read_n_logic::<T>(n, vec![])
}

fn read_n_logic<T: FromStr>(n: usize, mut a: Vec<T>) -> Vec<T> {
  match n {
    0 => a,
    _ => {
      a.push(read::<T>());
      read_n_logic(n - 1, a)
    }
  }
}

fn main() {
  let n = read::<usize>();
  let mut a = read_n::<usize>(n + 1);
  let mut b = read_n::<usize>(n);
  let mut answer = 0;

  a.reverse();
  b.reverse();

  for i in 0..b.len() {
    if b[i] > a[i] {
      answer += a[i];
      b[i] -= a[i];
      a[i] = 0;
    } else {
      answer += b[i];
      a[i] -= b[i];
      b[i] = 0;
    }

    if b[i] > a[i + 1] {
      answer += a[i + 1];
      b[i] -= a[i + 1];
      a[i + 1] = 0;
    } else {
      answer += b[i];
      a[i + 1] -= b[i];
      b[i] = 0;
    }
  }

  println!("{}", answer);
}
//  [swift]
let a=Int(readLine()!)!
var arr1=readLine()!.characters.split{$0==" "}.map{Int(String($0))!}
var arr2=readLine()!.characters.split{$0==" "}.map{Int(String($0))!}
var arr3 = arr1

var i = 0
var b = 0
var c = 0

for i in 0..<a {

  if( arr1[i] > arr2[i] ) {
    arr1[i] = arr1[i] - arr2[i]
  } else {
    var tmp = arr1[i]
    arr1[i] = 0
    arr2[i] = arr2[i] - tmp
    c = arr2[i]
    
    if( arr1[i+1] > c ) {
      arr1[i+1] = arr1[i+1] - c
    } else {
      arr1[i+1] = 0
      c = 0
    }
  }
}

for i in 0..<a + 1 {
  b += ( arr3[i] - arr1[i] )
}
print(b)
//  [swift]
import Foundation
import CoreFoundation

#if swift(>=4.0)
#else
extension String {
    func split(separator separator: Character) -> [String] {
        return self.characters.split(separator).map{String($0)}
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
extension Array where Element: Comparable {
    func max() -> Element? {
        return self.maxElement()
    }
    func min() -> Element? {
        return self.minElement()
    }
    func sorted() -> Array {
        return self.sort()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    func joined(separator separator: String = " ") -> String {
        return self.map{String($0)}.joinWithSeparator(separator)
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func reverse() {
        self = self.reversed()
    }
    func enumerated() -> EnumerateSequence<[Element]> {
        return self.enumerate()
    }
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: Character = " ") -> [String] {
    return readLine()!.split(separator: separator)
}
func readIntSplit(by separator: Character = " ") -> [Int] {
    return readLine()!.split(separator: separator).map{Int($0)!}
}
infix operator ** { associativity right precedence 155 }    // 右結合，乗除算より強くビットシフトより弱い
func **(lhs: Int, rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
func **(lhs: Int, rhs: Double) -> Double {
    return pow(Double(lhs), rhs)
}
//func gcd(_ x: Int, _ y: Int) -> Int {
//    return y>0 ? gcd(y, x%y) : x
//}
//func lcm(_ x: Int, _ y: Int) -> Int {
//    return x * y / gcd(x, y)
//}

/*************** テストスペース ***************/

//arr.sort{$0.0==$1.0 ? $0.1<$1.1 : $0.0<$1.0}  // タプル配列のソート
//print("Ready")

/*************** メインプログラム ***************/

let N = readInt()!
var A = readIntSplit()
let sum = A.reduce(0){$0+$1}
let B = readIntSplit()
for i in 0..<N {
    if A[i] < B[i] {
        A[i+1] = max(A[i+1]-(B[i]-A[i]), 0)
        A[i] = 0
    } else {
        A[i] -= B[i]
    }
}
print(sum - A.reduce(0){$0+$1})
//  [typescript]
// general helpers
const debug = (message?: any, ...optionalParams: any[]) => {
  if (process.env.LOCAL_DEBUG === '1') console.log(message, ...optionalParams)
}

// helpers
const parseLines = (
  lines: string[]
): { N: number, A: number[], B: number[] } => {
  const N = +lines[0]
  const A = lines[1].split(' ').map(line => +line)
  const B = lines[2].split(' ').map(line => +line)
  const obj = { N, A, B }
  debug(obj)
  return obj
}

// solver
export const solve = (lines: string[]): string => {
  const { N, A: monsters, B: heros } = parseLines(lines)

  let killed = 0
  for (let i = 0; i < N; i++) {
    if (heros[i] > monsters[i]) {
      killed += monsters[i]
      const remainPower = heros[i] - monsters[i]
      if (remainPower >= monsters[i+1]) {
        killed += monsters[i+1]
        monsters[i+1] = 0
      } else {
        killed += remainPower
        monsters[i+1] = monsters[i+1] - remainPower
      }
    } else {
      killed += heros[i]
    }
  }
  return `${killed}`
}

// main
const main = (lines: string[]) => {
  console.log(solve(lines))
}

// exec main function for submit
if (process.env.LOCAL_DEBUG !== '1') {
  const { stdin: input, stdout: output } = process
  input.resume()
  input.setEncoding('utf8')
  const lines: string[] = []
  require('readline')
    .createInterface({ input, output })
    .on('line', (line: string) => lines.push(line))
    .on('close', () => main(lines))
}
//  [typescript]
// general helpers
const debug = (message?: any, ...optionalParams: any[]) => {
  if (process.env.LOCAL_DEBUG === '1') console.log(message, ...optionalParams)
}

// helpers
const parseLines = (
  lines: string[]
): { N: number, A: number[], B: number[] } => {
  const N = +lines[0]
  const A = lines[1].split(' ').map(line => +line)
  const B = lines[2].split(' ').map(line => +line)
  const obj = { N, A, B }
  debug(obj)
  return obj
}

// solver
export const solve = (lines: string[]): string => {
  const { N, A: monsters, B: heros } = parseLines(lines)

  let killed = 0
  for (let i = 0; i < N; i++) {
    if (heros[i] === monsters[i]) {
      killed += monsters[i]
      continue
    }
    if (heros[i] > monsters[i]) {
      killed += monsters[i]
      const remainPower = heros[i] - monsters[i]
      if (remainPower >= monsters[i+1]) {
        killed += monsters[i+1]
        monsters[i+1] = 0
      } else {
        killed += remainPower
        monsters[i+1] = monsters[i+1] - remainPower
      }
    } else {
      killed += heros[i]
    }
  }
  return `${killed}`
}

// main
const main = (lines: string[]) => {
  console.log(solve(lines))
}

// exec main function for submit
if (process.env.LOCAL_DEBUG !== '1') {
  const { stdin: input, stdout: output } = process
  input.resume()
  input.setEncoding('utf8')
  const lines: string[] = []
  require('readline')
    .createInterface({ input, output })
    .on('line', (line: string) => lines.push(line))
    .on('close', () => main(lines))
}
//  [typescript]
'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'));
//  [python]
import numpy as np
w,h,n = map(int, input().split())
d = np.array([[1]*w for _ in range(h)], dtype=int)
for _ in range(n):
  x,y,a = map(int, input().split())
  for i in range(w):
    for j in range(h):
      if a==1 and i<x:
        d[j][i] = 0
      elif a==2 and x<=i:
        d[j][i] = 0
      elif a==3 and j<y:
        d[j][i] = 0
      elif a==4 and y<=j:
        d[j][i] = 0
  #print(d)
print(sum(sum(x) for x in d))
//  [python]
import numpy as np
w,h,n=map(int,input().split())
xya=[list(map(int,input().split())) for i in range(n)]
x=[xya[i][0] for i in range(n)]
y=[xya[i][1] for i in range(n)]
a=[xya[i][2] for i in range(n)]
s=np.array([[1]*w]*h)

for i in range(n):
  for j in range(h):
    for k in range(w):
      if a[i]==1 and k<x[i]:
        s[j,k]=0
      elif a[i]==2 and k>=x[i]:
        s[j,k]=0
      elif a[i]==3 and j<y[i]:
        s[j,k]=0
      elif a[i]==4 and j>=y[i]:
        s[j,k]=0
print(sum(sum(s)))
//  [python]
import numpy as np
H, W, N = map(int, input().split())

L = np.ones((W,H))
for i in range(N):
  x, y, a = map(int, input().split())
  if a == 1:
    for i in range(x):
      for j in range(W):
        L[j][i] = 0
  elif a == 2:
    for i in range(x, H):
      for j in range(W):
        L[j][i] = 0
  elif a == 3:
    for i in range(y):
      for j in range(H):
        L[i][j] = 0
  elif a == 4:
    for i in range(y, W):
      for j in range(H):
        L[i][j] = 0

print (int(np.sum(L)))
//  [java]


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int W = sc.nextInt();
        int H = sc.nextInt();
        int N = sc.nextInt();

        int [][] points=new int[N][3];

        for(int i=0;i<N;i++){
            points[i][0]=sc.nextInt();
            points[i][1]=sc.nextInt();
            points[i][2]=sc.nextInt();
        }

        int x0 = 0;
        int y0 = 0;
        int x1 = W;
        int y1 = H;

        for(int i=0;i<N;i++){

            switch (points[i][2]){
                case 1:
                    if(points[i][0]>x0) {
                        x0 = points[i][0];
                    }
                        break;
                case 2:
                    if(points[i][0]<x1) {
                        x1 = points[i][0];
                    }
                    break;
                case 3:
                    if(points[i][1]>y0) {
                        y0 = points[i][1];
                    }
                    break;
                case 4:
                    if(points[i][1]<y1) {
                        y1 = points[i][1];
                    }
                    break;
            }


        }


        if(x0<x1&&y0<y1){
            System.out.println((x1-x0)*(y1-y0));
        }
        else{
            System.out.println(0);
        }

        sc.close();

    }

}
//  [java]
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int W = Integer.parseInt(scan.next());
        int H = Integer.parseInt(scan.next());
        int N = Integer.parseInt(scan.next());

        int[] xs = new int[N];
        int[] ys = new int[N];
        int[] as = new int[N];


        for(int n=0;n<N;n++){
            xs[n] = Integer.parseInt(scan.next());
            ys[n] = Integer.parseInt(scan.next());
            as[n] = Integer.parseInt(scan.next());
        }

        scan.close();

        int[] impoint = new int[4];

        impoint[0] = 0;
        impoint[1] = W;
        impoint[2] = 0;
        impoint[3] = H;

        for(int i=0;i<N;i++){
            switch (as[i]){
                case 1: //left
                    if(xs[i] > impoint[0]){
                        impoint[0] = xs[i];
                    }
                    break;
                case 2://right
                    if(xs[i] < impoint[1]){
                        impoint[1] = xs[i];
                    }
                    break;
                case 3://down
                    if(ys[i] > impoint[2]){
                        impoint[2] = ys[i];
                    }
                    break;
                case 4://up
                    if(ys[i] < impoint[3]){
                        impoint[3] = ys[i];
                    }
                    break;
            }
        }
        System.out.println(Math.max(impoint[1] - impoint[0] , 0) * Math.max(impoint[3] - impoint[2],0));

    }
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int W = sc.nextInt();
        int H = sc.nextInt();
        int N = sc.nextInt();
        int[] x = new int[N];
        int[] y = new int[N];
        int[] a = new int[N];
        for (int i = 0; i < N; ++i) {
            x[i] = sc.nextInt();
            y[i] = sc.nextInt();
            a[i] = sc.nextInt();
        }

        System.out.println(solve(W, H, x, y, a));

        sc.close();
    }

    static int solve(int W, int H, int[] x, int[] y, int[] a) {
        boolean[][] grid = new boolean[H][W];
        for (int i = 0; i < x.length; ++i) {
            if (a[i] == 1) {
                for (int r = 0; r < H; ++r) {
                    for (int c = 0; c < x[i]; ++c) {
                        grid[r][c] = true;
                    }
                }
            } else if (a[i] == 2) {
                for (int r = 0; r < H; ++r) {
                    for (int c = x[i]; c < W; ++c) {
                        grid[r][c] = true;
                    }
                }
            } else if (a[i] == 3) {
                for (int r = 0; r < y[i]; ++r) {
                    for (int c = 0; c < W; ++c) {
                        grid[r][c] = true;
                    }
                }
            } else {
                for (int r = y[i]; r < H; ++r) {
                    for (int c = 0; c < W; ++c) {
                        grid[r][c] = true;
                    }
                }
            }
        }

        return Arrays.stream(grid).mapToInt(line -> (int) IntStream.range(0, W).filter(c -> !line[c]).count()).sum();
    }
}
//  [cpp]
#include<bits/stdc++.h>

using namespace std;

#define debug(n) cerr << #n << ':' << n << endl;
#define dline    cerr << __LINE__ << endl;

using ll = long long;
template<class T, class U> using P = pair<T,U>;
template<class T> using Heap = priority_queue<T>;
template<class T> using heaP = priority_queue<T,vector<T>,greater<T>>;
template<class T,class U> using umap = unordered_map<T,U>;
template<class T> using uset = unordered_set<T>;

template<class T>
bool ChangeMax(T&a,const T&b){
  if(a >= b) return false;
  a = b;    return true;
}

template<class T>
bool ChangeMin(T&a,const T&b){
  if(a <= b) return false;
  a = b;    return true;  
}

template<class T, size_t N, class U>
void Fill(T (&a)[N], const U&v){
    fill((U*)a,(U*)(a+N),v);
}

template<class T>
istream& operator >> (istream&is, vector<T>&v){
  for(auto&e:v)is >> e;
  return is;
}

int main(){
  int w,h,n; cin >> w >> h >> n;
  vector<int> x(n),y(n),a(n);
  set<P<int,int>>st;
  for(int i = 0; i < n; ++i)cin >> x[i] >> y[i] >> a[i];
  for(int i = 0; i < n; ++i){    
    for(int j = 1; j <= w; ++j){
      for(int k = 1; k <= h; ++k){
	if(a[i] == 1 && j <= x[i])st.emplace(j,k);
	if(a[i] == 2 && j > x[i])st.emplace(j,k);
	if(a[i] == 3 && k <= y[i])st.emplace(j,k);
	if(a[i] == 4 && k > y[i])st.emplace(j,k);
      }
    }
  }
  cout << w*h - st.size() << endl;
  return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

#define mp make_pair
#define pb push_back
typedef pair<int,int> p;

int main()
{
  int w,h,d=0,n,x,y,a;
  cin>>w>>h>>n;
  vector<p> v(w*h);
  for(int i=0;i<w;i++)
    for(int j=1;j<=h;j++)
      v[d++] = mp(i,j);
  //cout<<d<<"\n";
  while(n--)
  {
    cin>>x>>y>>a;
    vector<int> er;
    switch(a)
    {
      case 1:{
        for(int i=0;i<v.size();i++)
        {
          if(v[i].first<x)
            er.pb(i);
        }
        for(int i=0;i<er.size();i++)
          v.erase(v.begin()+er[i]-i);

        er.clear();
            break;}
      case 2:{
      for(int i=0;i<v.size();i++)
      {
        if(v[i].first>=x)
          er.pb(i);
      }
      for(int i=0;i<er.size();i++)
        v.erase(v.begin()+er[i]-i);

      er.clear();

            break;}
      case 3:{
      for(int i=0;i<v.size();i++)
      {
        if(v[i].second<=y)
          er.pb(i);
      }
      for(int i=0;i<er.size();i++)
        v.erase(v.begin()+er[i]-i);

      er.clear();
            break;}
      case 4:
      {for(int i=0;i<v.size();i++)
      {
        if(v[i].second>y)
          er.pb(i);
      }
      for(int i=0;i<er.size();i++)
        v.erase(v.begin()+er[i]-i);

      er.clear();
            break;
          }
    }
  }
  /*for(auto i:v)
    cout<<i.first<<" "<<i.second<<"\n";*/
  cout<<v.size()<<"\n";

  return 0;
}
//  [c]
#include<stdio.h>
 
int main(){
    int w,h,n;
    scanf("%d%d%d",&w,&h,&n);
    int right=w;
    int left=0;
    int up=h;
    int down=0;
    int x[n],y[n],a[n];
    for(int i=0;i<n;i++){
        scanf("%d%d%d",&x[i],&y[i],&a[i]);
        if(a[i]==1){
            if(x[i]>left){
                left=x[i];
            }
        }else if(a[i]==2){
            if(right>x[i]){
                right=x[i];
            }
        }else if(a[i]==3){
            if(y[i]>down){
                down=y[i];
            }
        }else if(a[i]==4){
            if(up>y[i]){ 
                up=y[i];
            }
        }
    }
    if(left>right||down>up){
        printf("0\n");
    }else{
        printf("%d\n",(right-left)*(up-down));
    }
    return 0;
}
//  [c]
#include<stdio.h>
int main(){
  int w,h,n,i;
  scanf("%d%d%d",&w,&h,&n);
  int mass[n+1][3];
  int left=0,right=w,up=h,down=0;
  for(i=0;i<n;i++){
    scanf("%d%d%d",&mass[i][0],&mass[i][1],&mass[i][2]);
    if(mass[i][2]==1){
      if(left<mass[i][0])
        left=mass[i][0];
    }
    else if(mass[i][2]==2){
      if(right>mass[i][0])
        right=mass[i][0];
    }
    else if(mass[i][2]==3){
      if(down<mass[i][1])
        down=mass[i][1];
    }
    else{
      if(up>mass[i][1])
        up=mass[i][1];
    }
  }
  if(up-down<0 || right-left<0)
    puts("0");
  else
    printf("%d\n",(up-down)*(right-left));
  return 0;
}
//  [c]
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
typedef long long LL;
#define rep(i,n) for(LL i=0; i<(LL)(n); i++)

//qsort
int compare_int(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
}

//比較
int max(int a, int b){
	if (a>b) return a;
	else return b;
}

int min(int a,int b) {
	if(a>b) return b;
	else return a;
}


//main関数
int main(){
	int W,H,N;
	scanf("%d %d %d",&W,&H,&N);
	int xx[N],yy[N],aa[N];
	rep( i , N) {
		scanf("%d %d %d",&xx[i],&yy[i],&aa[i]);
	}
	
	int ans[100][100] = {0};
	rep( i,N ){
		if(aa[i] == 1){
			for( int j=0; j < xx[i] ; j++){
				for( int k=0; k < H; k++ ){
					ans[j][k] = 1;
				} 
			}
		}
		else if (aa[i] == 2){
			for( int j=xx[i]; j < W ; j++){
				for( int k=0; k < H; k++ ){
					ans[j][k] = 1;
				} 
			}
		}
		else if (aa[i] == 3){
			for( int j=0; j < yy[i] ; j++){
				for( int k=0; k < W; k++ ){
					ans[k][j] = 1;
				} 
			}
		}
		else if (aa[i] == 4){
			for( int j=yy[i]; j < H ; j++){
				for( int k=0; k < W; k++ ){
					ans[k][j] = 1;
				} 
			}
		}	
	}
	int res = 0;
	rep( i,W ){
		rep( j,H ){
			if( ans[i][j] == 0){
				res++;
			}
		}
	}
	printf("%d",res);
}
//  [javascript]
'use strict'

const main = (input) => {
    input = input.split('\n').map(v => v.split(' ').map(v => parseInt(v)))
    const w = input[0][0]
    const h = input[0][1]
    const n = input[0][2]
    const arr = input.slice(1, n + 1)

    let first = {
        x: 0,
        y: 0,
    }

    let last = {
        x: w,
        y: h,
    }

    arr.forEach(v => {
        if(v[2] === 1){
            if(first.x < v[0]){
                first.x = v[0]
            }
        }
        if(v[2] === 2){
            if(last.x > v[0]){
                last.x = v[0]
            }
        }
        if(v[2] === 3){
            if(first.y < v[1]){
                first.y = v[1]
            }
        }
        if(v[2] === 4){
            if(last.y > v[1]){
                last.y = v[1]
            }
        }
    })
    if(first.x < last.x && first.y < last.y){
        console.log((last.x - first.x) * (last.y - first.y))
    }else{
        console.log(0)
    }
}

main(require('fs').readFileSync('/dev/stdin', 'utf-8'))
//  [javascript]
// https://atcoder.jp/contests/abc047/tasks/abc047_b
"use strict";
function Main(input) {
  const [basePoint, ...points] = input.trim().split("\n");
  const [W, H, N] = basePoint.trim().split(" ").map(Number);
  const field = Array(W)
    .fill()
    .map(() => Array(H).fill(1));

  for (let i = 0; i < N; i++) {
    const [x, y, a] = points[i].trim().split(" ").map(Number);

    let [jmin, jmax, kmin, kmax] = [0, 0, 0, 0];
    if (a === 1) {
      [jmin, jmax, kmin, kmax] = [0, x, 0, H];
    } else if (a === 2) {
      [jmin, jmax, kmin, kmax] = [x, W, 0, H];
    } else if (a === 3) {
      [jmin, jmax, kmin, kmax] = [0, W, 0, y];
    } else if (a === 4) {
      [jmin, jmax, kmin, kmax] = [0, W, y, H];
    }

    for (let j = jmin; j < jmax; j++) {
      for (let k = kmin; k < kmax; k++) {
        field[j][k] = 0;
      }
    }
  }

  const area = field.flat().reduce((acc, cur) => acc + cur, 0);
  console.log(area);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

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

func out(x ...interface{}) {
	//	fmt.Println(x...)
}

var sc = bufio.NewScanner(os.Stdin)

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

func getString() string {
	sc.Scan()
	return sc.Text()
}

type Data struct {
	x, y, a int
}

func main() {
	sc.Split(bufio.ScanWords)

	W := getInt()
	H := getInt()
	N := getInt()
	d := make([]Data, N)
	for i := 0; i < N; i++ {
		d[i].x = getInt()
		d[i].y = getInt()
		d[i].a = getInt()
	}

	var r [100][100]int
	out(W, H, N, d)

	for _, v := range d {
		switch v.a {
		case 1: // x < xi
			out("1:", v.x)
			for y := 0; y < H; y++ {
				for x := 0; x < v.x; x++ {
					out(x, y)
					r[y][x] = 1
				}
			}
		case 2: // x > xi
			out("2:")
			for y := 0; y < H; y++ {
				for x := v.x; x < W; x++ {
					out(x, y)
					r[y][x] = 1
				}
			}
		case 3: // y < yi
			out("3:")
			for y := 0; y < v.y; y++ {
				for x := 0; x < W; x++ {
					r[y][x] = 1
				}
			}
		case 4: // y > yi
			out("4:")
			for y := v.y; y < H; y++ {
				for x := 0; x < W; x++ {
					r[y][x] = 1
				}
			}
		}
	}

	ans := 0

	for y := 0; y < H; y++ {
		for x := 0; x < W; x++ {
			if r[y][x] == 0 {
				ans++
			}
			//			fmt.Print(r[y][x])
		}
		//		fmt.Println("")
	}
	fmt.Println(ans)
}