Problem:
Score: 600 points

Problem Statement

There is a grass field that stretches infinitely.

In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).

There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).

What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print INF instead.

Constraints

All values in input are integers between -10^9 and 10^9 (inclusive).

1 \leq N, M \leq 1000

A_i < B_i\ (1 \leq i \leq N)

E_j < F_j\ (1 \leq j \leq M)

The point (0, 0) does not lie on any of the given segments.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M

Output

If the area of the region the cow can reach is infinite, print INF; otherwise, print an integer representing the area in \mathrm{cm^2}.

(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)

Sample Input 1

5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4

Sample Output 1

13

The area of the region the cow can reach is 13\ \mathrm{cm^2}.

Sample Input 2

6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4

Sample Output 2

INF

The area of the region the cow can reach is infinite.

Solution in Rust (1.42.0) (judge verdict: Wrong Answer)

#![allow(unused_imports)]
#![allow(non_snake_case, unused)]

use std::cmp::*;
use std::collections::*;
use std::ops::*;

// https://atcoder.jp/contests/hokudai-hitachi2019-1/submissions/10518254

macro_rules! eprint {
	($($t:tt)*) => {{
		use ::std::io::Write;
		let _ = write!(::std::io::stderr(), $($t)*);
	}};
}
macro_rules! eprintln {
	() => { eprintln!(""); };
	($($t:tt)*) => {{
		use ::std::io::Write;
		let _ = writeln!(::std::io::stderr(), $($t)*);
	}};
}
macro_rules! dbg {
	($v:expr) => {{
		let val = $v;
		eprintln!("[{}:{}] {} = {:?}", file!(), line!(), stringify!($v), val);
		val
	}}
}

macro_rules! mat {
	($($e:expr),*) => { Vec::from(vec![$($e),*]) };
	($($e:expr,)*) => { Vec::from(vec![$($e),*]) };
	($e:expr; $d:expr) => { Vec::from(vec![$e; $d]) };
	($e:expr; $d:expr $(; $ds:expr)+) => { Vec::from(vec![mat![$e $(; $ds)*]; $d]) };
}

macro_rules! ok {
	($a:ident$([$i:expr])*.$f:ident()$(@$t:ident)*) => {
		$a$([$i])*.$f($($t),*)
	};
	($a:ident$([$i:expr])*.$f:ident($e:expr$(,$es:expr)*)$(@$t:ident)*) => { {
		let t = $e;
		ok!($a$([$i])*.$f($($es),*)$(@$t)*@t)
	} };
}

pub fn readln() -> String {
	let mut line = String::new();
	::std::io::stdin().read_line(&mut line).unwrap_or_else(|e| panic!("{}", e));
	line
}

macro_rules! read {
	($($t:tt),*; $n:expr) => {{
		let stdin = ::std::io::stdin();
		let ret = ::std::io::BufRead::lines(stdin.lock()).take($n).map(|line| {
			let line = line.unwrap();
			let mut it = line.split_whitespace();
			_read!(it; $($t),*)
		}).collect::<Vec<_>>();
		ret
	}};
	($($t:tt),*) => {{
		let line = readln();
		let mut it = line.split_whitespace();
		_read!(it; $($t),*)
	}};
}

macro_rules! _read {
	($it:ident; [char]) => {
		_read!($it; String).chars().collect::<Vec<_>>()
	};
	($it:ident; [u8]) => {
		Vec::from(_read!($it; String).into_bytes())
	};
	($it:ident; usize1) => {
		$it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1
	};
	($it:ident; [usize1]) => {
		$it.map(|s| s.parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1).collect::<Vec<_>>()
	};
	($it:ident; [$t:ty]) => {
		$it.map(|s| s.parse::<$t>().unwrap_or_else(|e| panic!("{}", e))).collect::<Vec<_>>()
	};
	($it:ident; $t:ty) => {
		$it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<$t>().unwrap_or_else(|e| panic!("{}", e))
	};
	($it:ident; $($t:tt),+) => {
		($(_read!($it; $t)),*)
	};
}


pub fn main() {
	let _ = ::std::thread::Builder::new().name("run".to_string()).stack_size(32 * 1024 * 1024).spawn(run).unwrap().join();
}

const MOD: u32 = 1_000_000_007;
const INF: i64 = std::i64::MAX/2;

// https://github.com/hatoo/competitive-rust-snippets/blob/master/src/binary_search.rs

use std::cmp::Ordering;

/// Equivalent to std::lowerbound and std::upperbound in c++
pub trait BinarySearch<T> {
    fn lower_bound(&self, x: &T) -> usize;
    fn upper_bound(&self, x: &T) -> usize;
}

impl<T: Ord> BinarySearch<T> for [T] {
    // 配列a内のv以上の最小のindex
    fn lower_bound(&self, x: &T) -> usize {
        let mut low = 0;
        let mut high = self.len();

        while low != high {
            let mid = (low + high) / 2;
            match self[mid].cmp(x) {
                Ordering::Less => {
                    low = mid + 1;
                }
                Ordering::Equal | Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
    // 配列a内のvより大きいの最小のindex
    fn upper_bound(&self, x: &T) -> usize {
        let mut low = 0;
        let mut high = self.len();

        while low != high {
            let mid = (low + high) / 2;
            match self[mid].cmp(x) {
                Ordering::Less | Ordering::Equal => {
                    low = mid + 1;
                }
                Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
}

fn solve() {
    let (n,m) = read!(usize,usize);
    let abc = read!(i64,i64,i64;n);
    let def = read!(i64,i64,i64;m);
    let mut clist = abc.iter().map(|&(a,b,c)| c).collect::<Vec<i64>>();
    clist.sort();
    clist.dedup();
    let mut dlist = def.iter().map(|&(d,e,f)| d).collect::<Vec<i64>>();
    dlist.sort();
    dlist.dedup();
    let mut clines = vec![vec![];clist.len()];
    for &(a,b,c) in &abc {
        let idx = clist.binary_search(&c).unwrap();
        clines[idx].push((a,b));
    }
    let mut nclines = vec![vec![];clist.len()];
    for i in 0..clines.len() {
        clines[i].sort();
        nclines[i].push(clines[i][0]);
        for j in 0..clines[i].len() {
            let s = clines[i][j].0;
            let t = clines[i][j].1;
            let nidx = nclines[i].len()-1;
            let ps = nclines[i][nidx].0;
            let pt = nclines[i][nidx].1;
            if pt >= s {
                nclines[i][nidx] = (ps,max(t,pt));
            }
            else {
                nclines[i].push((s,t));
            }
        }
    }
    let mut dlines = vec![vec![];dlist.len()];
    for &(d,e,f) in &def {
        let idx = dlist.binary_search(&d).unwrap();
        dlines[idx].push((e,f));
    }
    let mut ndlines = vec![vec![];dlist.len()];
    for i in 0..dlines.len() {
        dlines[i].sort();
        ndlines[i].push(dlines[i][0]);
        for j in 0..dlines[i].len() {
            let s = dlines[i][j].0;
            let t = dlines[i][j].1;
            let nidx = ndlines[i].len()-1;
            let ps = ndlines[i][nidx].0;
            let pt = ndlines[i][nidx].1;
            if pt >= s {
                ndlines[i][nidx] = (ps,max(t,pt));
            }
            else {
                ndlines[i].push((s,t));
            }
        }
    }
    let mut rooms = vec![vec![-1,-1,-1,-1,0];(nclines.len()-1)*(ndlines.len()-1)];
    let mut number = 0;
    let mut s = -1;
    for j in 0..ndlines.len()-1 {
        for i in 0..nclines.len()-1 {
            println!("{} {} {} {}", clist[i], clist[i+1], dlist[j], dlist[j+1]);
            let mut idx = nclines[i].upper_bound(&(dlist[j],dlist[j+1]));
            println!("{}", idx);
            if idx==0 || !(nclines[i][idx-1].0 <= dlist[j] && nclines[i][idx-1].1 >= dlist[j+1]) {
                if i==0 {
                    rooms[number][0] = -2;
                }
                else{
                    rooms[number][0] = number as i64 - 1;
                }
            }
            idx = nclines[i+1].upper_bound(&(dlist[j],dlist[j+1]));
            if idx==0 || !(nclines[i+1][idx-1].0 <= dlist[j] && nclines[i+1][idx-1].1 >= dlist[j+1]) {
                if i==nclines.len()-2 {
                    rooms[number][1] = -3;
                }
                else{
                    rooms[number][1] = number as i64 + 1;
                }
            }
            idx = ndlines[j].upper_bound(&(clist[i],clist[i+1]));
            if idx==0 || !(ndlines[j][idx-1].0 <= clist[i] && ndlines[j][idx-1].1 >= clist[i+1]) {
                if j==0 {
                    rooms[number][2] = -4;
                }
                else{
                    rooms[number][2] = (number - (nclines.len()-1)) as i64;
                }
            }
            idx = ndlines[j+1].upper_bound(&(clist[i],clist[i+1]));
            if idx==0 || !(ndlines[j+1][idx-1].0 <= clist[i] && ndlines[j+1][idx-1].1 >= clist[i+1]) {
                if j==ndlines.len()-2 {
                    rooms[number][3] = -5;
                }
                else{
                    rooms[number][3] = (number + (nclines.len()-1)) as i64;
                }
            }
            let area = (clist[i+1]-clist[i]).abs() * (dlist[i+1]-dlist[i]).abs();
            rooms[number][4] = area;
            if clist[i]<=0 && clist[i+1]>=0 && dlist[j]<=0 && dlist[j+1]>=0 {
                s = number as i64;
            }
            number += 1;
        }
    }
    let mut seen = vec![false;number];
    let mut cur = s;
    let mut ans = 0;
    loop {
        // println!("{}", cur);
        if cur<0 {
            println!("INF");
            return;
        }
        if seen[cur as usize] {
            break;
        }
        seen[cur as usize] = true;
        ans += rooms[cur as usize][4];
        // println!("{:?}", rooms[cur as usize]);
        for i in 0..4 {
            let nxt = rooms[cur as usize][i];
            if nxt==-1 {
                continue;
            }
            if nxt<=-2 {
                println!("INF");
                return;
            }
            if seen[nxt as usize] {
                continue;
            }
            cur = nxt;
            break;
        }
    }
    println!("{}", ans);
}

fn run() {
    solve();
}