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

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

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

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

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

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

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

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

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

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

// =========
//  [swift]
// 🐋💭
import Foundation

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

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

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

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

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

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

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

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = index(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    var monsters = readInts()
    var heroes = readInts()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力
    
    var ans = 0
    for i in 0..<n{
        ans             += min(heroes[i], monsters[i])
        heroes[i]       -= min(heroes[i], monsters[i])
        monsters[i]     -= min(heroes[i], monsters[i])
        ans             += min(heroes[i], monsters[i + 1])
        monsters[i + 1] -= min(heroes[i], monsters[i + 1])
    }
    print(ans)
}
main()
//  [swift]
let N = Int(readLine()!)!
var A = readLine()!.characters.split(" ").map{Int(String($0))!}
let B = readLine()!.characters.split(" ").map{Int(String($0))!}
var ans = 0
for i in 0..<N {
    let a = min(A[i], B[i])
    let b = min(A[i+1], B[i]-a)
    A[i+1] -= b
    ans += a+b
}
print(ans)
//  [swift]
let N = Int(readLine()!)!
var A = readLine()!.characters.split(" ").map{Int(String($0))!}
let B = readLine()!.characters.split(" ").map{Int(String($0))!}
var ans = 0
for i in 0..<N {
  ans += min(min(A[i],B[i])+A[i+1],B[i])
  A[i+1] -= min(A[i+1],B[i]-min(A[i],B[i]))
}
print(ans)
//  [swift]
// 🐋💭
import Foundation

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

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

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

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

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

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

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

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = index(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}

func main() {
    let n = readInt()
    var monsters = readInts()
    var heroes = readInts()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力
    
    var ans = 0
    for i in 0..<n{
        if heroes[i] >= monsters[i] && monsters[i] > 0{
            ans += monsters[i]
            heroes[i] -= monsters[i]
            ans += min(heroes[i], monsters[i + 1])
            monsters[i + 1] -= heroes[i]
            
        } else {
            ans += heroes[i]
        }
    }
    print(ans)
}
main()
//  [swift]
let N = Int(readLine()!)!
var A = readLine()!.characters.split(" ").map{Int(String($0))!}
let B = readLine()!.characters.split(" ").map{Int(String($0))!}
var ans = 0
for i in 0..<N {
    ans += min(min(A[i],B[i])+A[i+1],B[i])
    A[i]-=min(A[i],B[i])
}
print(ans)
//  [swift]
let N=Int(readLine()!)!,A=readLine()!.characters.split(" ").map{Int(String($0))!},B=readLine()!.characters.split(" ").map{Int(String($0))!}
print((0..<N).reduce(0){$0+min(min(A[$1],B[$1])+A[$1+1],B[$1])})
//  [typescript]
export class Main {
  static main(input): string {
    const tmp: string[] = input.split("\n");
    const n: number = parseInt(tmp[0].split(" ")[0]);
    const a: number[] = tmp[1].split(" ").slice(0, n + 1).map(int => parseInt(int));
    const b: number[] = tmp[2].split(" ").slice(0, n).map(int => parseInt(int));
    let result: number = 0;
    let remain: number = 0;
    for (let i = 0; i < n; i++) {
      if (a[i] <= remain + b[i]) {
        result += a[i];
        remain = b[i] - (Math.max(a[i] - remain, 0));
      } else {
        result += b[i] + remain;
        remain = 0;
      }
    }
    if (a[n] <= remain) {
      result += a[n];
    } else {
      result += remain;
    }
    return `${result}`;
  }
}
 console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));
//  [typescript]
function main(input) {
  input = input.trim().split("\n");
  const n = Number(input[0]);
  const as = input[1].split(" ").map(n => Number(n));
  const bs = input[2].split(" ").map(n => Number(n));
  let result = 0;
  for(let i = 0; i < n; i++) {
    const a = as[i];
    const nextA = as[i+1];
    const b = bs[i];
    if (b <= a) {
      result += b;
      continue;
    }
    result += a;
    const remainedB = b - a;
    if (remainedB <= nextA) {
      as[i+1] -= remainedB;
      result += remainedB;
      continue;
    }
    result += nextA;
    as[i+1] = 0;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
class NormalInput{
  input: string[];
  pointer: number;
  constructor(raw:string){
    this.input=raw.split(/ |\n/);
    this.pointer=0;
  }
  int():number{
    const ret= parseInt(this.input[this.pointer], 10);
    this.pointer++;
    return ret;
  }  
  ints(length:number):number[]{
    let ret:number[]=[];
    for(let i=0;i<length;i++){
      ret.push(this.int());
    }
    return ret;
  }
  str():string{
    const ret= this.input[this.pointer];
    this.pointer++;
    return ret;
  }
  strs(length:number):string[]{
    let ret:string[]=[];
    for(let i=0;i<length;i++){
      ret.push(this.str());
    }
    return ret;
  }
}
function Main(_:NormalInput) {
  const N=_.int();
  const A=_.ints(N+1);
  const B=_.ints(N);
  let count=0;
  for(let i=0;i<N;i++){
    const v=Math.min(A[i],B[i]);
    B[i]-=v;
    count+=v;

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

//DO NOT EDIT
Main(new NormalInput(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [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'));
//  [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)
    const beforeA = Array.from(a)
    let bi = 0
    for (let i = 0; i <= n; i++) {
        while (a[i] !== 0) {
            if (b[bi] === 0 || (b[bi] === 0 && bi === i-1)) {
                bi++
            }
            if (bi === n || ( bi > i)) {
                break
            }
            a[i]--
            b[bi]--
        }
    }
    console.log(sum(beforeA) - sum(a));
}

const sum = (arr: number[]) => {
    let sum = 0
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i]
    }
    return sum
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [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)
    const beforeA = Array.from(a)
    let bi = 0
    for (let i = 0; i <= n; i++) {
        while (a[i] !== 0) {
            if (b[bi] === 0 || (b[bi] === 0 && bi === i-1)) {
                bi++
            }
            if (bi === n || ( bi > i)) {
                break
            }
            a[i]--
            b[bi]--
        }
    }
    console.log(sum(beforeA) - sum(a));
}

const sum = (arr: number[]) => {
    return arr.reduce((acc, current) => acc + current)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [python]
w, h, n = map(int, input().split())
b = 0
l = 0

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

print(max(h - b, 0)*max(w - l, 0))
//  [python]
w, h, n = list(map(int, input().split()))
x_min, x_max, y_min, y_max = 0, w, 0, h
for _ in range(n):
    x, y, a = list(map(int, input().split()))
    if a == 1:
        x_min = max(x_min, x)
    elif a == 2:
        x_max = min(x_max, x)
    elif a == 3:
        y_min = max(y_min, y)
    else:
        y_max = min(y_max, y)
if x_min >= x_max or y_min >= y_max:
    print(0)
else:
    print((x_max - x_min) * (y_max - y_min))
//  [python]
w,h,n = list(map(int, input().split()))
data = [list(map(int, input().split())) for _ in range(n)]
x1 = y1 = 0
x2,y2 = w,h
for x,y,a in data:
    if a==1:
        x1=max(x1, x)
    elif a==2:
        x2=min(x2, x)
    elif a==3:
        y1=max(y1, y)
    else:
        y2=min(y2, y)
print(max(x2-x1,0)*max(y2-y1,0))
//  [python]
from collections import deque,defaultdict,Counter
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from bisect import bisect_left,bisect_right
from math import sqrt,gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode
import sys
sys.setrecursionlimit(10 ** 6)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

def S():
    return input()

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

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

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

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

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


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

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

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

s = abs(xe-xs)*abs(ye-ys)
if s<0:
    print(0)
else:
    print(s)
//  [python]
from collections import deque,defaultdict,Counter
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from bisect import bisect_left,bisect_right
from math import sqrt,gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode
import sys
sys.setrecursionlimit(10 ** 6)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

def S():
    return input()

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

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

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

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

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


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

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

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

s = (xe-xs)*(ye-ys)
if s<0:
    print(0)
else:
    print(s)
//  [python]
from collections import deque,defaultdict,Counter
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from bisect import bisect_left,bisect_right
from math import sqrt,gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode
import sys
sys.setrecursionlimit(10 ** 6)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

def S():
    return input()

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

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

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

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

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


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

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

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

s = (xe-xs)*(ye-ys)
if s<0:
    print(0)
else:
    print(s)
//  [java]
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import static java.lang.Math.max;
import static java.lang.Math.min;



public class Main {
    public static void main(String[] args) {
        FastScanner fsc = new FastScanner();
        int w=fsc.nextInt();
        int h=fsc.nextInt();
        int n=fsc.nextInt();
        int l=0, r=w, b=0, t=h;
        for(int i=0;i<n;i++){
            int x=fsc.nextInt();
            int y=fsc.nextInt();
            int a=fsc.nextInt();
            if(a==1){
                l=max(l, x);
            } else if(a==2){
                r=min(r, x);
            } else if(a==3){
                b=max(b, y);
            } else{
                t=min(t, y);
            }
        }
        System.out.println(l<=r && b<=t?(r-l)*(t-b):0);
    }
}


class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }
    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }
    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }
    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }
    public double nextDouble() { return Double.parseDouble(next());}
}
//  [java]
import java.util.*;
 class ck {

 public static void main(String[] args) {
   Scanner no=new Scanner(System.in);
   int n=no.nextInt();
   int u=n;
   int m=no.nextInt();
   int minx=0;
   int maxx=n;
   int miny=0;
   int maxy=m;
   int v=m;
   int t=no.nextInt();
   for(int i=0;i<t;i++){
     int a=no.nextInt();
     int b=no.nextInt();
     int y=no.nextInt();
    /* 5 4 2
     2 1 1
     3 3 4*/
     if(y==1){
       if(a>minx){
         minx=a;
       }
       //u=a;
     }
     else if(y==2){
      if(maxx>a){
        maxx=a;
      }
      // a=a-n;
     }
     else if(y==3){
      if(b>miny){
        miny=b;
      }
       //v=b;
     }
     else{
      if(maxy>b){
        maxy=b;
      }
      // v=b-m;
     }
   }
   if(minx>=maxx||miny>=maxy){
     System.out.println("0");
   }
   else System.out.println((maxx-minx)*(maxy-miny));
 }

}
//  [java]
import java.util.*;
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];
        int ans;
        int yoko0 = 0,yoko = w,tate0 = 0,tate = h; 
        for(int i = 0;i < n; i++){
          x[i] = sc.nextInt();
          y[i] = sc.nextInt();
          a[i] = sc.nextInt();
        }
        
      
        for(int i = 0;i < n;i++){
        	if(a[i] == 1 && yoko0 < x[i]){
              yoko0 = x[i];
            }else if(a[i] == 2 && yoko > x[i]){
              yoko = x[i];
            }else if(a[i] == 3 && tate0 < y[i]){
              tate0 = y[i];
            }else if(a[i] == 4 && tate > y[i]){
              tate = y[i];
            }
        }
        ans = (yoko - yoko0) * (tate - tate0);
        if(ans < 0){ans = 0;}
        System.out.println(ans);
    }
}
//  [java]
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        Main m = new Main(sc);
        m.show(m.solve());
        sc.close();
    }
    
	//フィールド
    Scanner sc;
    int W;
    int H;
    int N;
    int[] x;
    int[] y;
    int[] a;
    
    //入力
    Main(Scanner sc) {
        this.sc = sc;
        this.W = sc.nextInt();
        this.H = sc.nextInt();
        this.N = sc.nextInt();
        x = new int[N];
        y = new int[N];
        a = new int[N];
        for (int i=0; i<N; i++) {
        	x[i] = sc.nextInt();
        	y[i] = sc.nextInt();
        	a[i] = sc.nextInt();
        }
    }
    
    //解答処理
    private int solve() {
        int answer = 0;
        
        int lx = 0; //長方形左下のx座標
        int ly = 0; //長方形左下のy座標
        int rx = W; //長方形右上のx座標
        int ry = H; //長方形右上のy座標
        //右下と左上は(W,0)、(0,H)
        
        for(int i=0; i<N; i++){
          if(a[i] == 1){ //x[i]>xの領域を塗りつぶす
            lx = Math.max(lx, x[i]);
          }else if(a[i] == 2){ //x[i]<xの領域を塗りつぶす
            rx = Math.min(rx, x[i]);
          }else if(a[i] == 3){ //y[i]>yの領域を塗りつぶす
            ly = Math.max(ly, y[i]);
          }else if(a[i] == 4){ //y[i]<yの領域を塗りつぶす
            ry = Math.min(ry, y[i]);
          }
        }
        
        answer = (rx-lx) * (ry-ly);
        if (answer < 0) {
        	answer = 0;
        }
        return answer;
    }
    
    //出力
    public void show(int answer) {
        System.out.println(answer);
    }

}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
using vec=vector<ll>;
using mat=vector<vec>;
#define For(i,a,b) for(i=a;i<b;i++)
#define rep(i,N) For(i,0,N)
#define rep1(i,N) For(i,1,N)
#define all(v) (v).begin(),(v).end()
#define allr(v) (v).rbegin(),(v).rend()
#define vsort(v) sort(all(v))
#define vrsort(v) sort(allr(v))
#define mod 1000000007
using datas=pair<ll,ll>;

long mmid(long a,long b,long c){return a<b?(b<c?b:max(a,c)):(b>c?b:min(a,c));}

ll modinv(ll a) {
  ll b=mod,u=1,v=0,t;
  while(b){
    t=a/b;
    a-=t*b; swap(a,b);
    u-=t*v; swap(u,v);
  }
  return (u+mod)%mod;
}

ll moddevide(ll a,ll b){return (a*modinv(b))%mod;}

ll modncr(ll n,ll r){
  ll i,plus=1;
  rep(i,r){
    plus=(plus*(n-i))%mod;
    plus=moddevide(plus,i+1);
  }
  return plus;
}

ll euclidean_gcd(ll a, ll b) {
  if(a<b) return euclidean_gcd(b, a);
  ll r;
  while ((r=a%b)){a=b;b=r;}
  return b;
}

ll countdigits(ll n){
  ll ans=0;
  while(n){n/=10;ans++;}
  return ans;
}

ll sumdigits(ll n){
  ll ans=0;
  while(n){ans+=n%10;n/=10;}
  return ans;
}

void printmap(vector<ll>& a,ll H,ll W){
  ll i,j;
  For(i,0,H+2){
    For(j,0,W+2){cout<<a[i*(W+2)+j];}
    cout<<endl;
  }
}
void inputmap(vector<ll>& a,ll H,ll W){
  ll i,j;
  string ss;
  For(i,1,H+1){
    cin>>ss;
    For(j,1,W+1){
      if(ss[j-1]=='#'){
        a[i*(W+2)+j]=1;
      }else{
        a[i*(W+2)+j]=0;
      }
    }
  }
}

int main(){
  ll i,a,b,c,N,H,W,x=0,y=0;
  cin>>W>>H>>N;
  rep(i,N){
    cin>>a>>b>>c;
    switch(c){
      case 1:
        x=max(a,x);
      break;
      case 2:
        W=min(a,W);
      break;
      case 3:
        y=max(b,y);
      break;
      case 4:
        H=min(b,H);
      break;
    }
  }
  if(x>=W||y>=H){
    cout<<0<<endl;
  }else{
    cout<<(W-x)*(H-y)<<endl;
  }
  return 0;
}
//  [cpp]
#pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/numeric/interval.hpp>
#include <boost/numeric/interval/io.hpp>
using namespace::std;
namespace mp = boost::multiprecision;
typedef mp::number<mp::cpp_dec_float<32,int64_t>> cfloat;
typedef mp::cpp_int cint;
typedef long long lint;
typedef long long ll;
typedef long double ldouble;
typedef vector<lint> vec;
typedef vector<vector<lint>> mat;
typedef vector<vector<vector<lint>>> mat3;
typedef vector<double> dvec;
typedef vector<vector<double>> dmat;
typedef vector<vector<vector<double>>> dmat3;
typedef vector<string> svec;
typedef vector<vector<string>> smat;
typedef vector<vector<vector<string>>> smat3;
typedef vector<pair<lint,lint>> pvec;
typedef vector<vector<pair<lint,lint>>> pmat;
typedef vector<vector<vector<pair<lint,lint>>>> pmat3;
#define rep(i, n) for(lint i = 0; i < (lint)(n); i++)
#define irep(i) for(lint i = 0;; i++)
#define irep1(i) for(lint i = 1;; i++)
#define irep2(i) for(lint i = 2;; i++)
#define rrep(i, n) for(lint i = (lint)(n-1); i >-1; i--)
#define rrepi(i,a,b) for(lint i = (lint)(b-1); i >a-1; i--)
#define repi(i,a,b) for(lint i=lint(a);i<lint(b);i++)
#define rep2(i,a,b,c) for(lint i=lint(a);i>lint(b);i+=c)
#define all(x) (x).begin(),(x).end()
#define PI 3.141592653589793
#define cout (cout<<fixed<<setprecision(15))
#define dist(x1,y1,x2,y2) (pow(pow(x2-x1,2)+pow(y2-y1,2),0.5))
#define output(v) do{bool f=0;for(auto i:v){cout<<(f?" ":"")<<i;f=1;}cout<<"\n";}while(0)
#define output2(v) for(auto i:v)output(i);
#define input(a,n) lint n;cin>>n;vector<lint>a(n);rep(i,n)cin>>a[i];
#define sum(v) accumulate(all(v),0LL)
#define INF (1LL<<60)
#define IINF (1<<30)
#define LINF 9223372036854775807
#define MOD 1000000007
vector<lint> dx={-1,1,0,0,1,1,-1,-1};
vector<lint> dy={0,0,-1,1,1,-1,1,-1};
inline lint gcd(lint a,lint b){return b?gcd(b,a%b):a;}
inline lint lcm(lint a,lint b){return a*b/gcd(a,b);}
class Comb{
    public:
    vector<lint> fac,ifac;
    lint M=1000000;
    Comb(){
        fac.resize(M+1);
        ifac.resize(M+1);
        fac[0] = 1;
        ifac[0] = 1;
        rep(i,M){
            fac[i+1] = fac[i]*(i+1) % MOD;
            ifac[i+1] = ifac[i]*mpow(i+1, MOD-2) % MOD;
        }
    }
    lint mpow(lint x, lint n){
        lint ans = 1;
        while(n != 0){
            if(n&1) ans = ans*x % MOD;
            x = x*x % MOD;
            n = n >> 1;
        }
        return ans;
    }
    lint comb(lint a, lint b){
        if(a == 0 && b == 0)return 1;
        if(a < b || a < 0)return 0;
        lint tmp = ifac[a-b]* ifac[b] % MOD;
        return tmp * fac[a] % MOD;
    }
};
int main(){
    lint w,h,n;
    cin>>w>>h>>n;
    vec x(n),y(n),a(n);
    rep(i,n)cin>>x[i]>>y[i]>>a[i];
    lint s=0,t=0,u=w,r=h;
    rep(i,n){
        if(a[i]==1)s=max(s,x[i]);
        if(a[i]==2)u=min(u,x[i]);
        if(a[i]==3)t=max(t,y[i]);
        if(a[i]==4)r=min(r,y[i]);
    }
    cout<<max(0LL,u-s)*max(0LL,r-t);
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define PI 3.141592653589793
#define MOD 1000000007
#define rep(i, n) for (ll i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
typedef long long ll;
typedef long double ld;


int main(){
    ll H, W, N;
    cin >> H >> W >> N;
    ll x0 = 0, x1 = W, y0 = 0, y1 = H;
    rep(i, N){
        ll x, y, a;
        cin >> x >> y >> a;
        if(a==1)
            x0 = max(x, x0);
        if(a==2)
            x1 = min(x, x1);
        if(a==3)
            y0 = max(y, y0);
        if(a==4)
            y1 = min(y, y1);
    }

    cout << max(x1 - x0, 0LL) * max(y1 - y0, 0LL) << endl;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define PI 3.141592653589793
#define MOD 1000000007
#define rep(i, n) for (ll i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
typedef long long ll;
typedef long double ld;


int main(){
    ll Square[100][100] = {0};
    ll H, W, N;
    cin >> H >> W >> N;

    rep(j,H){
        rep(i,W){
            Square[j][i] = 1;
        }
    }

    rep(i, N){
        ll x, y, a;
        cin >> x >> y >> a;
        x--;
        y--;
        if(a == 1){
            rep(j,H){
                rep(i,W){
                    if(i < x){
                        Square[j][i] = 0;
                    }
                    
                }
            }
        }
        if(a == 2){
            rep(j,H){
                rep(i,W){
                    if(i > x){
                        Square[j][i] = 0;
                    }
                    
                }
            }
        }

        if(a == 3){
            rep(j,H){
                rep(i,W){
                    if(j < y){
                        Square[j][i] = 0;
                    }
                    
                }
            }
        }
        if(a == 4){
            rep(j,H){
                rep(i,W){
                    if(j > y){
                        Square[j][i] = 0;
                    }
                    
                }
            }
        }
    }
    ll ans = 0;
    rep(j,H){
        rep(i,W){
            ans += Square[j][i];
        }
    }

    cout << ans << endl;
}
//  [cpp]
//  すぬけ君の塗り絵 2 イージー  WA
#include <bits/stdc++.h>
using namespace std;

int main(){
    int W, H, N;
    cin >> W >> H >> N;
    int x[N], y[N], a[N];
    for(int i=0; i<N; i++){
        cin >> x[i] >> y[i] >> a[i];
    }
    int xl=0, yd=0;
    int xr=W, yu=H;
    for(int i=0; i<N; i++){
        if(a[i]==1){
            xl=max(xl, x[i]);
        }
        if(a[i]==2){
            xr=min(xr, x[i]);
        }
        if(a[i]==3){
            yd=max(yd, y[i]);
        }
        if(a[i]==4){
            yu=min(yu, y[i]);
        }
    }
    
    int s=(xr-xl)*(yu-yd);
    if(s>=0){
        cout << s << endl;
    }
    else{
        cout << 0 << endl;
    }
    return 0;
}
//  [c]
#include<stdio.h>
int main()
{
	int w,h,n,x,y,a,x0=0,y0=0;

	scanf("%d%d%d",&w,&h,&n);
	while(n--){
		scanf("%d%d%d",&x,&y,&a);
		if(a==1&&x0<x)
			x0=x;
		else if(a==2&&w>x)
			w=x;
		else if(a==3&&y0<y)
			y0=y;
		else if(a==4&&h>y)
			h=y;
		if(w<x0||h<y0){
			puts("0");
			return 0;
		}
	}
	printf("%d",(w-x0)*(h-y0));
	return 0;
}
//  [c]
#include <stdio.h>

#define N_MAX 100
#define W_MAX 100
#define H_MAX 100

int main()
{
    int w, h, n;
    int points[N_MAX][2];
    int commands[N_MAX];

    scanf("%d %d %d", &w, &h, &n);
    for (int i = 0; i < n; i++)
    {
	scanf("%d", &points[i][0]);
	scanf("%d", &points[i][1]);
	scanf("%d", &commands[i]);
    }

    int area[W_MAX][H_MAX] = {};
    for (int i = 0; i < n; i++)
    {
	switch (commands[i])
	{
	    case 1:
		for (int x = 0; x < points[i][0]; x++)
		{
		    for (int y = 0; y < h; y++)
		    {
			area[x][y] = 1;
		    }
		}
		break;
	    case 2:
		for (int x = points[i][0]; x < w; x++)
		
		{
		    for (int y = 0; y < h; y++)
		    {
			area[x][y] = 1;
		    }
		}
		break;
	    case 3:
		for (int x = 0; x < w; x++)
		{
		    for (int y = 0; y < points[i][1]; y++)
		    {
			area[x][y] = 1;
		    }
		}
		break;
	    case 4:
		for (int x = 0; x < w; x++)
		{
		    for (int y = points[i][1]; y < h; y++)
		    {
			area[x][y] = 1;
		    }
		}
		break;
	}
    }

    int count = 0;
    for (int x = 0; x < w; x++)
    {
	for (int y = 0; y < h; y++)
	{
	    if (area[x][y] == 0)
	    {
		count++;
	    }
	}
    }
    printf("%d\n", count);
    
    return 0;
}
//  [c]
# include"stdio.h"

int main(){
    int w,h,n;
    scanf("%d %d %d",&w,&h,&n);
    int x[n],y[n],a[n],f[w][h];
    for(int i=0;i<n;i++)
        scanf("%d %d %d",&x[i],&y[i],&a[i]);
    for(int i=0;i<w;i++)
        for(int j=0;j<h;j++)
            f[i][j]=1;
    for(int i=0;i<n;i++){
        if(a[i]==1)
            for(int j=x[i]-1;j>=0;j--)
                for(int k=0;k<h;k++)
                    f[j][k]=0;
        if(a[i]==2)
            for(int j=x[i];j<w;j++)
                for(int k=0;k<h;k++)
                    f[j][k]=0;
        if(a[i]==3)
            for(int j=y[i]-1;j>=0;j--)
                for(int k=0;k<w;k++)
                    f[k][j]=0;
        if(a[i]==4)
            for(int j=y[i];j<h;j++)
                for(int k=0;k<w;k++)
                    f[k][j]=0;
    }
    int ans=0;
    for(int i=0;i<w;i++)
        for(int j=0;j<h;j++)
            if(f[i][j]) ans++;
    printf("%d\n",ans);

}
//  [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){
            left=x[i];
        }else if(a[i]==2){
            right=x[i];
        }else if(a[i]==3){
            down=y[i];
        }else if(a[i]==4){
            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;
    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){
            left=x[i];
        }else if(a[i]==2){
            right=x[i];
        }else if(a[i]==3){
            down=y[i];
        }else if(a[i]==4){
            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>
#include<stdlib.h>
typedef long long ll;

int main() {
	ll w, h, n, x, y, a;
	scanf("%lld%lld%lld", &w, &h, &n);
	ll w1 = 0, w2 = w, h1 = 0, h2 = h;
	for (int i = 0; i < n; i++) {
		scanf("%lld%lld%lld", &x, &y, &a);
		switch (a) {
		case 1:
			if (x > w1) w1 = x;
			break;
		case 2:
			if (x < w2) w2 = x;
			break;
		case 3:
			if (y > h1) h1 = y;
			break;
		case 4:
			if (y < h2) h2 = y;
			break;
		}
	}
	printf("%lld", (w2 - w1) * (h2 - h1));

	return 0;
}
//  [javascript]
"use strict"
function Main(input) {
  input = input.trim().split('\n');
  let WHN = input[0].split(' ').map(Number);
  let minX = 0;
  let minY = 0;
  let maxX = WHN[0];
  let maxY = WHN[1];
  const N = WHN[2];
 
  for(let i=1; i<=N; i++){
    let tmp = input[i].trim().split(' ').map(Number)
    let A = tmp[2];
    if(A === 1){
      if(tmp[0] > minX){
        minX = tmp[0];
      }
    } else if (A === 2) {
      if(tmp[0] < maxX){
        maxX = tmp[0];
      }
    } else if (A === 3) {
      if(tmp[1] > minY) {
        minY = tmp[1];
      }
    } else if (A === 4) {
      if(tmp[1] < maxY) {
        maxY = tmp[1];
      }
    }
  }
 
  const X = maxX - minX;
  const Y = maxY - minY;
  if(X <= 0 || Y <= 0){
    console.log(0);
  } else {
    console.log(X*Y);
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";

var input = require("fs").readFileSync("/dev/stdin", "utf8");
var cin = input.split(/ |\n/),
    cid = 0;

function next() {
    return +cin[cid++];
} // number一個取得
function nextstr() {
    return cin[cid++];
} // 文字列一個取得
function nextbig() {
    return BigInt(cin[cid++]);
} // BigInteger一個取得
// 長さnの配列として取得。aは文字列フラグ
function nexts(n, a) {
    return a ? cin.slice(cid, cid += n) : cin.slice(cid, cid += n).map(a => +a);
}
// 長さnのBigInt配列として取得。
function nextsbig(n) {
    return cin.slice(cid, cid += n).map(a => BigInt(a));
}
// w個ずつを組にして長さhの配列。aは文字列フラグ。
function nextm(h, w, a) {
    var r = [],
        i = 0;
    if (a)
        for (; i < h; i++) r.push(cin.slice(cid, cid += w));
    else
        for (; i < h; i++) r.push(cin.slice(cid, cid += w).map(a => +a));
    return r;
}
// 多次元配列。v,a1,a2,a3 なら、3次元。[[値vで長さa3の配列]をa2個並べた配列]をa1個並べた配列。
function xArray(v) {
    var a = arguments,
        l = a.length,
        r = "Array(a[" + --l + "]).fill().map(x=>{return " + v + ";})";
    while (--l) r = "Array(a[" + l + "]).fill().map(x=>" + r + ")";
    return eval(r);
}


console.log(main().toString());

function main() {
    let w = next();
    let h = next();
    let n = next();
    let xya = nextm(n, 3)
    let t1 = [];
    let t2 = [];
    let t3 = [];
    let t4 = [];
    // xyaをaでソート
    // console.log({xya})
    xya.forEach(v => {
        if (v[2] == 1) t1.push(v)
        if (v[2] == 2) t2.push(v)
        if (v[2] == 3) t3.push(v)
        if (v[2] == 4) t4.push(v)
    });
    //console.log(t1,t2,t3,t4)
    t1 = t1.length > 0 ? t1.sort((a, b) => b[0] - a[0])[0][0] : 0
    t2 = t2.length > 0 ? t2.sort((a, b) => a[0] - b[0])[0][0] : w
    t3 = t3.length > 0 ? t3.sort((a, b) => b[1] - a[1])[0][1] : 0
    t4 = t4.length > 0 ? t4.sort((a, b) => a[1] - b[1])[0][1] : h

    //console.log(t1,t2,t3,t4)
    return Math.max(t2 - t1, 0) * Math.max(t4 - t3, 0)
}
//  [javascript]
"use strict"
function Main(input) {
  input = input.trim().split('\n');
  let WHN = input[0].split(' ').map(Number);
  let minX = 0;
  let minY = 0;
  let maxX = WHN[0];
  let maxY = WHN[1];
  const N = WHN[2];

  for(let i=1; i<=N; i++){
    let tmp = input[i].trim().split(' ').map(Number)
    let A = tmp[2];
    if(A === 1){
      if(tmp[0] > minX){
        minX = tmp[0];
      }
    } else if (A === 2) {
      if(tmp[0] < maxX){
        maxX = tmp[0];
      }
    } else if (A === 3) {
      if(tmp[1] > minY) {
        minY = tmp[1];
      }
    } else if (A === 4) {
      if(tmp[1] < maxY) {
        maxY = tmp[1];
      }
    }
  }

  const X = maxX - minX;
  const Y = maxY - minY;
  if(X <= 0 || Y <= 0){
    console.log(0);
  } else {
    console.log(X*Y);
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict'

let rect = [];

function Main(input) {
    const d = input.split('\n').map(v => v.split(' '));
    let s = d.shift();
    const W = Number(s[0]);
    const H = Number(s[1]);
    const N = Number(s[2]);

    rect = [];
    for (let i = 0; i < H; i++) {
        for (let j = 0; j < W; j++) {
            rect[i] = Array(W).fill(0);
        }
    }
    for (let i = 0; i < N; i++) {
        switch (Number(d[i][2])) {
            case 1:
                draw(0, d[i][0], 0, H);
                break;
            case 2:
                draw(d[i][0], W, 0, H);
                break;
            case 3:
                draw(0, W, 0, d[i][1]);
                break;
            case 4:
                draw(0, W, d[i][1], H);
                break;
            default:
                break;
        }
    }
    console.log(rect)

    let result = 0;
    for (const arr of rect) {
        for (const v of arr) {
            if (v === 0) {
                result++
            }
        }
    }

    console.log(result);
}

function draw(xStart, xEnd, yStart, yEnd) {
    for (let y = yStart; y < yEnd; y++) {
        for (let x = xStart; x < xEnd; x++) {
            rect[y][x] += 1;
        }
    }
}


Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
"use strict"
function Main(input) {
  input = input.trim().split('\n');
  let WHN = input[0].split(' ').map(Number);
  let minX = 0;
  let minY = 0;
  let maxX = WHN[0];
  let maxY = WHN[1];
  const N = WHN[2];

  for(let i=1; i<=N; i++){
    let tmp = input[i].trim().split(' ').map(Number)
    let A = tmp[2];
    if(A === 1){
      if(tmp[0] < maxX){
        minX = tmp[0];
      } else {
        minX = maxX;
      }
    } else if (A === 2) {
      if(tmp[0] > minX){
        maxX = tmp[0];
      } else {
        maxX = minX;
      }
    } else if (A === 3) {
      if(tmp[1] > minY) {
        minY = tmp[1];
      }
    } else if (A === 4) {
      if(tmp[1] > minY) {
        maxY = tmp[1];
      } else {
        maxY = minY;
      }
    }
  }

  let ret = (maxX - minX) * (maxY - minY);
  console.log(ret);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict"
function Main(input) {
  input = input.trim().split('\n');
  let WHN = input[0].split(' ').map(Number);
  let minX = 0;
  let minY = 0;
  let maxX = WHN[0];
  let maxY = WHN[1];
  const N = WHN[2];

  for(let i=1; i<=N; i++){
    let tmp = input[i].trim().split(' ').map(Number)
    let A = tmp[2];
    if(A === 1){
      if(tmp[0] < maxX){
        minX = tmp[0];
      } else {
        minX = maxX;
      }
    } else if (A === 2) {
      if(tmp[0] > minX){
        maxX = tmp[0];
      } else {
        maxX = minX;
      }
    } else if (A === 3) {
      if(tmp[1] < maxY) {
        minY = tmp[1];
      } else {
        minY = maxY;
      }
    } else if (A === 4) {
      if(tmp[1] > minY) {
        maxY = tmp[1];
      } else {
        maxY = minY;
      }
    }
  }

  let ret = (maxX - minX) * (maxY - minY);
  console.log(ret);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	sc.Scan()
	iv, _ := strconv.Atoi(sc.Text())
	return iv
}

func init() {
	sc.Split(bufio.ScanWords)
}

func max(x, y int) int {
	if x > y {
		return x
	}
	return y
}

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

func main() {
	w, h, n := scanInt(), scanInt(), scanInt()

	xl, xr := 0, w
	yl, yr := 0, h
	for i := 0; i < n; i++ {
		x, y, a := scanInt(), scanInt(), scanInt()
		switch a {
		case 1:
			xl = max(xl, x)
		case 2:
			xr = min(xr, x)
		case 3:
			yl = max(yl, y)
		case 4:
			yr = min(yr, y)
		}
	}
	if xr > xl && yr > yl {
		fmt.Println((xr - xl) * (yr - yl))
	} else {
		fmt.Println(0)
	}
}