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.



Sample input:
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:
13

Submission status: Time Limit Exceeded

Solution code:
import sys

# from collections import deque

max_int = 1000000001  # 10^9+1
min_int = -max_int

n, m = map(int, sys.stdin.readline().split())

xs = {0}
ys = {0}

hor = {}  # [x => [[a,b], [a,b]], ...]
ver = {}

for _n in range(n):
    a, b, c = map(int, sys.stdin.readline().split())
    xs.add(a)
    xs.add(b)
    ys.add(c)
    if c not in ver:
        ver[c] = [[a, b]]
    else:
        ver[c].append([a, b])

for _m in range(m):
    d, e, f = map(int, sys.stdin.readline().split())
    xs.add(d)
    ys.add(e)
    ys.add(f)
    if d not in hor:
        hor[d] = [[e, f]]
    else:
        hor[d].append([e, f])

xs = list(xs)
xs.sort()
x0 = 0
for i in range(len(xs)):
    if xs[i] == 0:
        x0 = i
        break

ys = list(ys)
ys.sort()
y0 = 0
for j in range(len(ys)):
    if ys[j] == 0:
        y0 = j
        break

if x0 == 0 or y0 == 0 or x0 == len(xs) - 1 or y0 == len(ys) - 1:
    print('INF')
    exit()

ans = 0
q = [(x0 - 1, y0 - 1, x0, y0)]
# pretends = [(x0 - 1, y0 - 1, x0, y0)]
visited = set()

while q:
    xl_, yl_, xr_, yr_ = q.pop()
    if (xl_, yl_, xr_, yr_) in visited:
        continue
    visited.add((xl_, yl_, xr_, yr_))
    if xl_ < 0 or yl_ < 0 or xr_ >= len(xs) or yr_ >= len(ys):
        print('INF')
        exit()
    xl = xs[xl_]
    xr = xs[xr_]
    yl = ys[yl_]
    yr = ys[yr_]
    ans += (xr - xl) * (yr - yl)
    if xl in hor:
        for lb, rb in hor[xl]:
            if lb <= yl and rb >= yr:
                break
        else:
            q.append((xl_ - 1, yl_, xr_ - 1, yr_))
    else:
        q.append((xl_ - 1, yl_, xr_ - 1, yr_))

    if xr in hor:
        for lb, rb in hor[xr]:
            if lb <= yl and rb >= yr:
                break
        else:
            q.append((xl_ + 1, yl_, xr_ + 1, yr_))
    else:
        q.append((xl_ + 1, yl_, xr_ + 1, yr_))

    if yl in ver:
        for ub, db in ver[yl]:
            if ub <= xl and db >= xr:
                break
        else:
            q.append((xl_, yl_ - 1, xr_, yr_ - 1))
    else:
        q.append((xl_, yl_ - 1, xr_, yr_ - 1))

    if yr in ver:
        for ub, db in ver[yr]:
            if ub <= xl and db >= xr:
                break
        else:
            q.append((xl_, yl_ + 1, xr_, yr_ + 1))
    else:
        q.append((xl_, yl_ + 1, xr_, yr_ + 1))
    # print(new_pretends, ans)
    # break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

max_int = 1000000001  # 10^9+1
min_int = -max_int

n, m = map(int, sys.stdin.readline().split())

xs = {0}
ys = {0}

hor = {}  # [x => [[a,b], [a,b]], ...]
ver = {}

for _n in range(n):
    a, b, c = map(int, sys.stdin.readline().split())
    xs.add(a)
    xs.add(b)
    ys.add(c)
    if c not in ver:
        ver[c] = [[a, b]]
    else:
        ver[c].append([a, b])

for _m in range(m):
    d, e, f = map(int, sys.stdin.readline().split())
    xs.add(d)
    ys.add(e)
    ys.add(f)
    if d not in hor:
        hor[d] = [[e, f]]
    else:
        hor[d].append([e, f])

xs = list(xs)
xs.sort()
x0 = 0
for i in range(len(xs)):
    if xs[i] == 0:
        x0 = i
        break

ys = list(ys)
ys.sort()
y0 = 0
for j in range(len(ys)):
    if ys[j] == 0:
        y0 = j
        break

if x0 == 0 or y0 == 0 or x0 == len(xs) - 1 or y0 == len(ys) - 1:
    print('INF')
    exit()

ans = 0
pretends = [(x0 - 1, y0 - 1, x0, y0)]
visited = set()
while pretends:
    new_pretends = []
    for xl_, yl_, xr_, yr_ in pretends:
        if (xl_, yl_, xr_, yr_) in visited:
            continue
        visited.add((xl_, yl_, xr_, yr_))
        if xl_ < 0 or yl_ < 0 or xr_ >= len(xs) or yr_ >= len(ys):
            print('INF')
            exit()
        xl = xs[xl_]
        xr = xs[xr_]
        yl = ys[yl_]
        yr = ys[yr_]
        ans += (xr - xl) * (yr - yl)
        if xl in hor:
            for lb, rb in hor[xl]:
                if lb <= yl and rb >= yr:
                    break
            else:
                new_pretends.append((xl_ - 1, yl_, xr_ - 1, yr_))
        else:
            new_pretends.append((xl_ - 1, yl_, xr_ - 1, yr_))

        if xr in hor:
            for lb, rb in hor[xr]:
                if lb <= yl and rb >= yr:
                    break
            else:
                new_pretends.append((xl_ + 1, yl_, xr_ + 1, yr_))
        else:
            new_pretends.append((xl_ + 1, yl_, xr_ + 1, yr_))

        if yl in ver:
            for ub, db in ver[yl]:
                if ub <= xl and db >= xr:
                    break
            else:
                new_pretends.append((xl_, yl_ - 1, xr_, yr_ - 1))
        else:
            new_pretends.append((xl_, yl_ - 1, xr_, yr_ - 1))

        if yr in ver:
            for ub, db in ver[yr]:
                if ub <= xl and db >= xr:
                    break
            else:
                new_pretends.append((xl_, yl_ + 1, xr_, yr_ + 1))
        else:
            new_pretends.append((xl_, yl_ + 1, xr_, yr_ + 1))
    pretends = new_pretends
    # print(new_pretends, ans)
    # break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=Y=[0]+f;R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):*a,c=I();R+=[(a,c)];Y+=[c];X+=a
for i in r(m):a,*b=I();H+=[(a,b)];X+=[a];Y+=b
def g(X):s=dict(enumerate(sorted(set(X))));return{s[i]:i for i in s},s,len(s)+1
h,s,K=g(X);w,t,L=g(Y);j=lambda:[[0]*-~K for i in r(L+1)];V=j();U=j();v=j()
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1
for i in r(L):
 for j in r(K):U[i][j+1]+=U[i][j];V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
 x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
 for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
  c=x+e;d=y+f
  if(K>c>=0<=d<L)*v[d][c]==0:
   if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=Y=[0]+f;R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):*a,b=I();R+=[(a,b)];Y+=b,;X+=a
for i in r(m):a,*b=I();H+=[(a,b)];X+=a,;Y+=b
def g(X):s=dict(enumerate(sorted(set(X))));return{s[i]:i for i in s},s,len(s)+1
h,s,K=g(X);w,t,L=g(Y);j=lambda:[[0]*-~K for i in r(L+1)];V=j();U=j();v=j()
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for a,(b,c)in H:V[w[b]][h[a]]+=1;V[w[c]][h[a]]+=-1
for i in r(L):
 for j in r(K):U[i][j+1]+=U[i][j];V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
 x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
 for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
  c=x+e;d=y+f
  if(K>c>=0<=d<L)*v[d][c]==0:
   if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=Y=[0]+f;R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):*a,b=I();R+=[(a,b)];Y+=b,;X+=a
for i in r(m):a,*b=I();H+=[(a,b)];X+=a,;Y+=b
def g(X):s=dict(enumerate(sorted(set(X))));return{s[i]:i for i in s},s,len(s)
h,s,K=g(X);w,t,L=g(Y);j=lambda:[[0]*(K+2)for i in r(L+2)];V=j();U=j();v=j()
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1
for i in r(L+1):
 for j in r(K+1):U[i][j+1]+=U[i][j];V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
 x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
 for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
  c=x+e;d=y+f
  if(K>c>=0<=d<L)*v[d][c]==0:
   if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=[0]+f;Y=X[:];R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):a,b,c=I();R+=[((a,b),c)];Y+=[c];X+=[a,b]
for i in r(m):a,b,c=I();H+=[(a,(b,c))];X+=[a];Y+=[b,c]
s=dict(enumerate(sorted(set(X))));K=len(s);t=dict(enumerate(sorted(set(Y))));L=len(t);h=dict(zip(s.values(),s.keys()));w=dict(zip(t.values(),t.keys()));V=[[0]*-~K for i in r(L+1)];U=[i[:]for i in V];v=[i[:]for i in V]
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for i in r(L):
 for j in r(K):U[i][j+1]+=U[i][j]
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1
for j in r(K):
 for i in r(L):V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
 x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
 for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
  c=x+e;d=y+f
  if(K>c>=0<=d<L)*v[d][c]==0:
   if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=set([0]+f);Y=set(X);R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):a,b,c=I();R+=[((a,b),c)];Y.add(c);X.add(a);X.add(b)
for i in r(m):a,b,c=I();H+=[(a,(b,c))];X.add(a);Y.add(b);Y.add(c)
s=dict(enumerate(sorted(X)));K=len(s);t=dict(enumerate(sorted(Y)));L=len(t);h=dict(zip(s.values(),s.keys()));w=dict(zip(t.values(),t.keys()));V=[[0]*-~K for i in r(L+1)];U=[i[:]for i in V];v=[i[:]for i in V]
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for i in r(L):
 for j in r(K):U[i][j+1]+=U[i][j]
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1
for j in r(K):
 for i in r(L):V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
 x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
 for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
  c=x+e;d=y+f
  if(K>c>=0<=d<L)*v[d][c]==0:
   if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=set([0]+f);Y=set(X);R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):a,b,c=I();R+=[((a,b),c)];Y.add(c);X.add(a);X.add(b)
for i in r(m):a,b,c=I();H+=[(a,(b,c))];X.add(a);Y.add(b);Y.add(c)
s=dict(enumerate(sorted(X)));K=len(s);t=dict(enumerate(sorted(Y)));L=len(t);h=dict(zip(s.values(),s.keys()));w=dict(zip(t.values(),t.keys()));V=[[0]*-~K for i in r(L+1)];U=[i[:]for i in V];v=[i[:]for i in V]
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for i in r(L+1):
 for j in r(K):U[i][j+1]+=U[i][j]
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1
for j in r(K+1):
 for i in r(L):V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
 x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
 for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
  c=x+e;d=y+f
  if(0<=c<K)*(0<=d<L)*(v[d][c]==0)*(U[-~f//2+y][x]==0if f!=0else V[y][-~e//2+x]==0):q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split());F=1<<65;r=range;n,m=I();f=[-F,F];X=set([0]+f);Y=set(X);R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):a,b,c=I();R+=[((a,b),c)];Y.add(c);X.add(a);X.add(b)
for i in r(m):a,b,c=I();H+=[(a,(b,c))];X.add(a);Y.add(b);Y.add(c)
s=dict(enumerate(sorted(X)));K=len(s);t=dict(enumerate(sorted(Y)));L=len(t);h=dict(zip(s.values(),s.keys()));w=dict(zip(t.values(),t.keys()));V=[[0]*-~K for i in r(L+1)];U=[i[:]for i in V];v=[i[:]for i in V]
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for i in r(L+1):
 for j in r(K):U[i][j+1]+=U[i][j]
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1
for j in r(K+1):
 for i in r(L):V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
 x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
 for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
  c=x+e;d=y+f
  if(0<=c<K)*(0<=d<L)*(v[d][c]==0)*(U[-~f//2+y][x]==0if f!=0else V[y][-~e//2+x]==0):q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)

Submission status: Time Limit Exceeded

Solution code:
import sys
import operator
from itertools import repeat
from functools import partial, reduce
from typing import Iterable, Tuple, Union

Indices = Union[int, slice, Tuple[Union[int, slice]]]

ndgetter = (
	lambda a: a,
	lambda a, i: a[i],
	lambda a, i, j: a[i][j],
	lambda a, i, j, k: a[i][j][k],
	lambda a, i, j, k, l: a[i][j][k][l],
	lambda a, i, j, k, l, m: a[i][j][k][l][m],
	lambda a, i, j, k, l, m, n: a[i][j][k][l][m][n],
	lambda a, i, j, k, l, m, n, o: a[i][j][k][l][m][n][o],
	lambda a, i, j, k, l, m, n, o, p: a[i][j][k][l][m][n][o][p],
	lambda a, i, j, k, l, m, n, o, p, q: a[i][j][k][l][m][n][o][p][q],
	lambda a, i, j, k, l, m, n, o, p, q, r: a[i][j][k][l][m][n][o][p][q][r],
)

class nd (list):
	def at(self, indices : Tuple[int]):
		return ndgetter[len(indices)](self, *indices)
	
	def set_at(self, indices : Tuple[int], value):
		ndgetter[len(indices) - 1](self, *indices[:-1])[indices[-1]] = value
	
	def fill(self, value):
		for i in range(len(self)):
			element = super().__getitem__(i)
			if isinstance(element, nd):
				element.apply_inplace(value)
			else:
				super().__setitem__(i, value)
	
	def apply(self, func):
		return type(self)(
			(
				element.apply(func)
				if isinstance(element, nd)
				else func(element)
			)
			for element in self
		)
	
	def apply_inplace(self, func):
		for i in range(len(self)):
			element = super().__getitem__(i)
			if isinstance(element, nd):
				element.apply_inplace(func)
			else:
				super().__setitem__(i, func(element))
	
	def operate(self, other, operator):
		if not isinstance(other, list):
			other = repeat(other)
		return type(self)(
			(
				element.operate(other_element, operator)
				if isinstance(element, nd)
				else operator(element, other_element)
			)
			for element, other_element in zip(self, other)
		)
	def roperate(self, other, operator):
		if not isinstance(other, list):
			other = repeat(other)
		return type(self)(
			(
				element.roperate(other_element, operator)
				if isinstance(element, nd)
				else operator(other_element, element)
			)
			for element, other_element in zip(self, other)
		)
	def ioperate(self, other, operator):
		if not isinstance(other, list):
			other = repeat(other)
		for i, (element, other_element) in enumerate(zip(self, other)):
			if isinstance(element, nd):
				element.ioperate(other_element, operator)
			else:
				super().__setitem__(i, operator(element, other_element))
		return self
	def rioperate(self, other, operator):
		if not isinstance(other, list):
			other = repeat(other)
		for i, (element, other_element) in enumerate(zip(self, other)):
			if isinstance(element, nd):
				element.rioperate(other_element, operator)
			else:
				super().__setitem__(i, operator(other_element, element))
		return self
	def __add__(self, other):
		return self.operate(other, operator.add)
	def __radd__(self, other):
		return self.roperate(other, operator.add)
	def __iadd__(self, other):
		return self.ioperate(other, operator.add)
	def __sub__(self, other):
		return self.operate(other, operator.sub)
	def __rsub__(self, other):
		return self.roperate(other, operator.sub)
	def __isub__(self, other):
		return self.ioperate(other, operator.sub)
	def __mul__(self, other):
		return self.operate(other, operator.mul)
	def __rmul__(self, other):
		return self.roperate(other, operator.mul)
	def __imul__(self, other):
		return self.ioperate(other, operator.mul)
	def __matmul__(self, other):
		return self.operate(other, operator.matmul)
	def __rmatmul__(self, other):
		return self.roperate(other, operator.matmul)
	def __imatmul__(self, other):
		return self.ioperate(other, operator.matmul)
	def __truediv__(self, other):
		return self.operate(other, operator.truediv)
	def __rtruediv__(self, other):
		return self.roperate(other, operator.truediv)
	def __itruediv__(self, other):
		return self.ioperate(other, operator.truediv)
	def __floordiv__(self, other):
		return self.operate(other, operator.floordiv)
	def __rfloordiv__(self, other):
		return self.roperate(other, operator.floordiv)
	def __ifloordiv__(self, other):
		return self.ioperate(other, operator.floordiv)
	def __mod__(self, other):
		return self.operate(other, operator.mod)
	def __rmod__(self, other):
		return self.roperate(other, operator.mod)
	def __imod__(self, other):
		return self.ioperate(other, operator.mod)
	def __divmod__(self, other):
		return self.operate(other, operator.divmod)
	def __rdivmod__(self, other):
		return self.roperate(other, operator.divmod)
	def __idivmod__(self, other):
		return self.ioperate(other, operator.divmod)
	def __pow__(self, other):
		return self.operate(other, operator.pow)
	def __rpow__(self, other):
		return self.roperate(other, operator.pow)
	def __ipow__(self, other):
		return self.ioperate(other, operator.pow)
	def __lshift__(self, other):
		return self.operate(other, operator.lshift)
	def __rlshift__(self, other):
		return self.roperate(other, operator.lshift)
	def __ilshift__(self, other):
		return self.ioperate(other, operator.lshift)
	def __rshift__(self, other):
		return self.operate(other, operator.rshift)
	def __rrshift__(self, other):
		return self.roperate(other, operator.rshift)
	def __irshift__(self, other):
		return self.ioperate(other, operator.rshift)
	def __and__(self, other):
		return self.operate(other, operator.and_)
	def __rand__(self, other):
		return self.roperate(other, operator.and_)
	def __iand__(self, other):
		return self.ioperate(other, operator.and_)
	def __xor__(self, other):
		return self.operate(other, operator.xor)
	def __rxor__(self, other):
		return self.roperate(other, operator.xor)
	def __ixor__(self, other):
		return self.ioperate(other, operator.xor)
	def __or__(self, other):
		return self.operate(other, operator.or_)
	def __ror__(self, other):
		return self.roperate(other, operator.or_)
	def __ior__(self, other):
		return self.ioperate(other, operator.or_)
	def __neg__(self, other):
		return self.apply(other, operator.neg)
	def __pos__(self, other):
		return self.apply(other, operator.pos)
	def __abs__(self, other):
		return self.apply(other, operator.abs)
	def __invert__(self, other):
		return self.apply(other, operator.invert)
	def __lt__(self, other):
		return self.operate(other, operator.lt)
	def __le__(self, other):
		return self.operate(other, operator.le)
	def __eq__(self, other):
		return self.operate(other, operator.eq)
	def __ne__(self, other):
		return self.operate(other, operator.ne)
	def __gt__(self, other):
		return self.operate(other, operator.gt)
	def __ge__(self, other):
		return self.operate(other, operator.ge)
	
	@classmethod
	def full(cls, fill_value, shape : Union[int, Tuple[int], Iterable[int]]):
		if isinstance(shape, int):
			return cls(repeat(fill_value, shape))
		elif not isinstance(shape, tuple):
			shape = tuple(shape)
		
		if len(shape) == 1:
			return cls(repeat(fill_value, shape[0]))
		else:
			return cls(
				map(
					partial(cls.full, fill_value),
					repeat(shape[1:], shape[0])
				)
			)
	
	@classmethod
	def fromiter(cls, iterable, ndim=1):
		if ndim == 1:
			return cls(iterable)
		else:
			return cls(
				cls.fromiter(element, ndim-1)
				for element in iterable
			)
	
	@classmethod
	def nones(cls, shape : Union[int, Tuple[int], Iterable[int]]):
		return cls.full(None, shape)
	
	@classmethod
	def zeros(cls, shape : Union[int, Tuple[int], Iterable[int]], type=int):
		return cls.full(type(0), shape)
	
	@classmethod
	def ones(cls, shape : Union[int, Tuple[int], Iterable[int]], type=int):
		return cls.full(type(1), shape)
	
	@classmethod
	def partial_map(cls, func, *left_args, **left_kwargs):
		def nd_func(a, *right_args, **right_kwargs):
			return cls.fromiter(
				func(*left_args, v, *right_args, **left_kwargs, **right_kwargs)
				for v in a
			)
		return nd_func
	
	@classmethod
	def vectorize(cls, func, *left_args, **left_kwargs):
		def nd_func(a : nd, *right_args, **right_kwargs):
			return a.apply(lambda v: func(
				*left_args, v, *right_args, **left_kwargs, **right_kwargs
			))
		return nd_func



def bytes_to_str(x : bytes):
	return x.decode('utf-8')

def inputs(func=bytes_to_str, sep=None, maxsplit=-1):
	return map(func, sys.stdin.buffer.readline().split(sep=sep, maxsplit=maxsplit))

def inputs_1d(func=bytes_to_str, **kwargs):
	return nd(inputs(func, **kwargs))

def inputs_2d(nrows : int, func=bytes_to_str, **kwargs):
	return nd.fromiter(
		(inputs(func, **kwargs) for _ in range(nrows)),
		ndim=2
	)

def inputs_2d_T(nrows : int, func=bytes_to_str, **kwargs):
	return nd.fromiter(
		zip(*(inputs(func, **kwargs) for _ in range(nrows))),
		ndim=2
	)

from collections import deque
import operator
from typing import Optional


class BreadthFirstSearch (object):
	def __init__(self, shape : Tuple[int]):
		self.shape = shape
		self.pushed = nd.zeros(shape, type=bool)
		self._deque = deque()
	
	def push(self, position : Tuple[int]):
		if not self.pushed.at(position):
			self.pushed.set_at(position, True)
			self._deque.append(position)
	
	def peek(self) -> Optional[Tuple[int]]:
		return self._deque[0] if self._deque else None
	
	def pop(self) -> Optional[Tuple[int]]:
		return self._deque.popleft() if self._deque else None
	
	def __bool__(self):
		return bool(self._deque)

from bisect import bisect_left, bisect_right


N, M = inputs(int)
A, B, C = inputs_2d_T(N, int)
D, E, F = inputs_2d_T(M, int)
xs = sorted(set(C))
ys = sorted(set(D))

x_guard = nd.zeros((len(xs)+1, len(ys)+1), type=bool)
y_guard = nd.zeros((len(xs)+1, len(ys)+1), type=bool)

C = nd.partial_map(bisect_right, xs)(C)
A = nd.partial_map(bisect_left, ys)(A)
A += 1
B = nd.partial_map(bisect_right, ys)(B)

D = nd.partial_map(bisect_right, ys)(D)
E = nd.partial_map(bisect_left, xs)(E)
E += 1
F = nd.partial_map(bisect_right, xs)(F)

for a, b, c in zip(A, B, C):
	for y in range(a, b):
		x_guard[c][y] = True

for d, e, f in zip(D, E, F):
	for x in range(e, f):
		y_guard[x][d] = True

cow = (
	bisect_right(xs, 0),
	bisect_right(ys, 0)
)

bfs = BreadthFirstSearch(shape=(len(xs)+1, len(ys)+1))
bfs.push(cow)

area = 0
while bfs:
	xi, yi = bfs.pop()
	
	if 0 < xi < len(xs) and 0 < yi < len(ys):
		area += (xs[xi] - xs[xi-1]) * (ys[yi] - ys[yi-1])
		if not x_guard[xi][yi]:
			bfs.push((xi-1, yi))
		if not x_guard[xi+1][yi]:
			bfs.push((xi+1, yi))
		if not y_guard[xi][yi]:
			bfs.push((xi, yi-1))
		if not y_guard[xi][yi+1]:
			bfs.push((xi, yi+1))
	else:
		area = 'INF'
		break

print(area)