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: Wrong Answer

Solution code:
import numpy as np

def main():
    N, M = map(int, input().split())
    area = N+M

    mapX = dict()
    mapY = dict()

    lh = []
    lw = []
    for i in range(area):
        if i <= N-1:
            a, b, c = map(int, input().split())
            mapX[a] = 0
            mapX[b] = 0
            mapY[c] = 0
            lh.append({'a':a, 'b':b, 'c':c})
        else:
            c, a, b = map(int, input().split())
            mapY[a] = 0
            mapY[b] = 0
            mapX[c] = 0
            lw.append({'a':a, 'b':b, 'c':c})

    mapXs = dict(sorted(mapX.items()))
    mapYs = dict(sorted(mapY.items()))

    xg = list()
    yg = list()

    for k in mapXs:
        mapXs[k] = len(xg)
        xg.append(k)

    for k in mapYs:
        mapYs[k] = len(yg)
        yg.append(k)

    #print(str(xg), '\n', str(yg))

    h = len(xg)*2
    w = len(yg)*2

    grid = np.zeros((h,w), int)

    for i in range(N):
        a = mapXs[lh[i]['a']]*2
        b = mapXs[lh[i]['b']]*2
        c = mapYs[lh[i]['c']]*2
        for j in range(a,b+1): grid[j][c] = -1

    for i in range(M):
        a = mapYs[lw[i]['a']]*2
        b = mapYs[lw[i]['b']]*2
        c = mapXs[lw[i]['c']]*2
        for j in range(a,b+1): grid[c][j] = -1

    #print('befor BFS\n', str(grid))

    que = dict()
    cdX = mapXs[next(iter(mapXs))]*2
    cdY = mapYs[next(iter(mapYs))]*2

    grid[cdX][cdY] = 1
    que = [[cdX,cdY]]

    dx = [0,-1,0,1]
    dy = [-1,0,1,0]

    while len(que) != 0:
        q = que.pop(0)
        for i in range(4):
            currentX = q[0]+dx[i]
            currentY = q[1]+dy[i]
            if currentX < 0 or currentX >= h: continue
            if currentY < 0 or currentY >= w: continue
            if grid[currentX][currentY] != 0: continue

            grid[currentX][currentY]=1
            que.append([currentX,currentY])

    #print('after BFS\n', str(grid))

    ans = 0
    for x in range(h):
        for y in range(w):
            if grid[x][y] != 1: continue
            if x%2 == 0 or y%2 == 0: continue
            if (x == 0 or x == h-1) or (y == 0 or y == w-1):
                print('INF')
                return
            
            ans += (xg[x%2+1]-xg[x%2])*(yg[y%2+1]-yg[y%2])

    print(ans)

if __name__=='__main__':
    main()

Submission status: Wrong Answer

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,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=sorted(set(X));l=len(s);return{s[i]:i for i in r(l)},s,l
h,s,K=g(X);w,t,L=g(Y);V,U,v=[[[0]*-~K for i in r(L+1)]for _ in r(3)];q=[(h[0],w[0])];a=0
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]
while q:
 x,y=q.pop();v[y][x]=1;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 1-v[d][c]and U[(f>0)+y][x]*f+V[y][(e>0)+x]*e==0:q+=(c,d),;v[d][c]=1
print([a,'INF'][a>F])

Submission status: Wrong Answer

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,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)
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 1-v[d][c]and(V[y][(e>0)+x]|f==0)|U[(f>0)+y][x]|e==0:q+=[(c,d)];v[d][c]=1
print([a,'INF'][a>F])

Submission status: Wrong Answer

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,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)
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 1-v[d][c]and U[(f>0)+y][x]|e==0|(V[y][(e>0)+x]|f==0):q+=[(c,d)];v[d][c]=1
print([a,'INF'][a>F])

Submission status: Wrong Answer

Solution code:
#168 - F
import sys
import numpy as np


def main():
    N, M = map(int, sys.stdin.buffer.readline().split())
    LineData = np.int64(sys.stdin.buffer.read().split())

    INF = 10**9 + 1

    LineData = LineData.reshape(-1, 3)
    A, B, C = LineData[:N].T
    D, E, F = LineData[N:].T
    X = np.unique(np.concatenate([D, [-INF, 0, INF]]))
    Y = np.unique(np.concatenate([C, [-INF, 0, INF]]))
    A = np.searchsorted(X, A)
    B = np.searchsorted(X, B, 'right') - 1
    C = np.searchsorted(Y, C)
    D = np.searchsorted(X, D)
    E = np.searchsorted(Y, E)
    F = np.searchsorted(Y, F, 'right') - 1

    LenX = len(X)
    LenY = len(Y)

    LineX = np.zeros((LenX, LenY), np.bool_)
    LineY = np.zeros((LenX, LenY), np.bool_)

    for x1, x2, y in zip(A, B, C):
        for x in range(x1, x2 + 1):
            LineY[x, y] = True

    for x, y1, y2 in zip(D, E, F):
        for y in range(y1, y2 + 1):
            LineX[x, y] = True
    
    visit = np.zeros((LenX, LenY), np.bool_)
    x = np.searchsorted(X, 0, 'right') - 1
    y = np.searchsorted(Y, 0, 'right') - 1
    visit[x, y] = True
    area = 0
    queue = [(x, y)]

    while queue:
        x, y = queue.pop()

        if x == 0 or x == LenX - 1 or y == 0 or y == LenY - 1:
            print("INF")
            break
        
        area += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])

        if not (LineX[x, y] and LineX[x, y + 1]) and not visit[x - 1, y]:
            visit[x - 1, y] = True
            queue.append((x - 1, y))
        if not (LineY[x, y] and LineY[x + 1, y]) and not visit[x, y - 1]:
            visit[x, y - 1] = True
            queue.append((x, y - 1))
        if not (LineX[x + 1, y] and LineX[x + 1, y + 1]) and not visit[x + 1, y]:
            visit[x + 1, y] = True
            queue.append((x + 1, y))
        if not (LineY[x, y + 1] and LineY[x + 1, y + 1]) and not visit[x, y + 1]:
            visit[x, y + 1] = True
            queue.append((x, y + 1))
    
    else:
        print(area)






if __name__ == '__main__':
	main()

sys.exit()

Submission status: Wrong Answer

Solution code:
I=lambda:[int(i) for i in input().split()]

ans=0
F=1<<65
n,m=I()
X=set([0,F,-F])
Y=set(X)
R=[]
H=[]
for i in range(n):
    a,b,c=I()
    R.append(((a,b),c))
    Y.add(c)
    X.add(a)
    X.add(b)
 
n+=2
R.append(((-F,F),F))
R.append(((-F,F),-F))
 
for i in range(m):
    a,b,c=I()
    H.append((a,(b,c)))
    X.add(a)
    Y.add(b)
    Y.add(c)
 
m+=2
H.append((F,(-F,F)))
H.append((-F,(-F,F)))

xdc={}
c=1
for j in sorted(X):
    xdc[c]=j
    c+=1
nx=c-1
 
ydc={}
c=1
for j in sorted(Y):
    ydc[c]=j
    c+=1
ny=c-1
 
xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))
 
V=[[0]*(nx+1+1) for i in range(ny+1+1)]
U=[i[:]for i in V]

for (a,b),c in R:
    U[ydcr[c]][xdcr[a]]+=1
    U[ydcr[c]][xdcr[b]]+=-1
for i in range(ny+1):
    for j in range(nx):
        U[i][j+1]+=U[i][j]
        
for d,(e,f) in H:
    V[ydcr[e]][xdcr[d]]+=1
    V[ydcr[f]][xdcr[d]]+=-1
for j in range(nx+1):
    for i in range(ny):
        V[i+1][j]+=V[i][j]

R=[[0]*(nx+1) for i in range(ny+1)]
q=[(xdcr[0],ydcr[0])]
R[ydcr[0]][xdcr[0]]=1

while q:
    cx,cy=q.pop()
    ans+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1])
    for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]:
        nbx=cx+dx
        nby=cy+dy
        if (0>nbx>=nx)or(0>nby>=ny)or R[nby][nbx]==1:
            continue
        if dy!=0:
            if U[-~dy//2+cy][cx]==0:
                q.append((nbx,nby))
                R[nby][nbx]=1
        else:
            if V[cy][-~dx//2+cx]==0:
                q.append((nbx,nby))
                R[nby][nbx]=1
if ans>=F:
    ans='F'
print(ans)

Submission status: Wrong Answer

Solution code:
I=lambda:[int(i) for i in input().split()]
F=1<<65
n,m=I()
X=set([0,F,-F])
Y=set(X)
R=[]
H=[]
for i in range(n):
    a,b,c=I()
    R.append(((a,b),c))
    Y.add(c)
    X.add(a)
    X.add(b)
 
n+=2
R+=[((-F,F),F),((-F,F),-F)]
 
for i in range(m):
    a,b,c=I()
    H.append((a,(b,c)))
    X.add(a)
    Y.add(b)
    Y.add(c)
 
m+=2
H+=[(F,(-F,F)),(-F,(-F,F))]

xdc={}
c=1
for j in sorted(X):
    xdc[c]=j
    c+=1
nx=c-1
 
ydc={}
c=1
for j in sorted(Y):
    ydc[c]=j
    c+=1
ny=c-1
 
xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))
 
V=[[0]*(nx+1+1) for i in range(ny+1+1)]
U=[i[:]for i in V]

for (a,b),c in R:
    U[ydcr[c]][xdcr[a]]+=1
    U[ydcr[c]][xdcr[b]]+=-1
for i in range(ny+1):
    for j in range(nx):
        U[i][j+1]+=U[i][j]
        
for d,(e,f) in H:
    V[ydcr[e]][xdcr[d]]+=1
    V[ydcr[f]][xdcr[d]]+=-1
for j in range(nx+1):
    for i in range(ny):
        V[i+1][j]+=V[i][j]

v=[[0]*(nx+1) for i in range(ny+1)]
q=[(xdcr[0],ydcr[0])]
v[ydcr[0]][xdcr[0]]=1

a=0
while q:
    cx,cy=q.pop()
    a+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1])
    for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]:
        nbx=cx+dx
        nby=cy+dy
        if (0>nbx>=nx)or(0>nby>=ny)or v[nby][nbx]==1:
            continue
        if dy!=0:
            if U[-~dy//2+cy][cx]==0:
                q.append((nbx,nby))
                v[nby][nbx]=1
        else:
            if V[cy][-~dx//2+cx]==0:
                q.append((nbx,nby))
                v[nby][nbx]=1
if a>=F:a='F'
print(a)

Submission status: Wrong Answer

Solution code:
I=lambda:[int(i) for i in input().split()]
F=1<<65
n,m=I()
X=set([0,F,-F])
Y=set(X)
R=[]
H=[]
for i in range(n):
    a,b,c=I()
    R.append(((a,b),c))
    Y.add(c)
    X.add(a)
    X.add(b)
 
n+=2
R+=[((-F,F),F),((-F,F),-F)]
 
for i in range(m):
    a,b,c=I()
    H.append((a,(b,c)))
    X.add(a)
    Y.add(b)
    Y.add(c)
 
m+=2
H+=[(F,(-F,F)),(-F,(-F,F))]

xdc={}
c=1
for j in sorted(X):
    xdc[c]=j
    c+=1
nx=c-1
 
ydc={}
c=1
for j in sorted(Y):
    ydc[c]=j
    c+=1
ny=c-1
 
xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))
 
V=[[0]*(nx+1+1) for i in range(ny+1+1)]
U=[i[:]for i in V]

for (a,b),c in R:
    U[ydcr[c]][xdcr[a]]+=1
    U[ydcr[c]][xdcr[b]]+=-1
for i in range(ny+1):
    for j in range(nx):
        U[i][j+1]+=U[i][j]
        
for d,(e,f) in H:
    V[ydcr[e]][xdcr[d]]+=1
    V[ydcr[f]][xdcr[d]]+=-1
for j in range(nx+1):
    for i in range(ny):
        V[i+1][j]+=V[i][j]

v=[[0]*(nx+1) for i in range(ny+1)]
q=[(xdcr[0],ydcr[0])]
v[ydcr[0]][xdcr[0]]=1

a=0
while q:
    
    cx,cy=q.pop()
    a+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1])
    for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]:
        k=0
        nbx=cx+dx
        nby=cy+dy
        if (0>nbx>=nx)or(0>nby>=ny)or v[nby][nbx]==1:
            continue
        if dy!=0:
            k=(U[-~dy//2+cy][cx]==0)
        else:
            k=(V[cy][-~dx//2+cx]==0)
        if k:
            q.append((nbx,nby));v[nby][nbx]=1
if a>=F:a='F'
print(a)

Submission status: Wrong Answer

Solution code:
I=lambda:[int(i) for i in input().split()]
F=1<<65
n,m=I()
X=set([0,F,-F])
Y=set(X)
R=[]
H=[]
for i in range(n):
    a,b,c=I()
    R.append(((a,b),c))
    Y.add(c)
    X.add(a)
    X.add(b)
 
n+=2
R+=[((-F,F),F),((-F,F),-F)]
 
for i in range(m):
    a,b,c=I()
    H.append((a,(b,c)))
    X.add(a)
    Y.add(b)
    Y.add(c)
 
m+=2
H+=[(F,(-F,F)),(-F,(-F,F))]

xdc={}
c=1
for j in sorted(X):
    xdc[c]=j
    c+=1
nx=c-1
 
ydc={}
c=1
for j in sorted(Y):
    ydc[c]=j
    c+=1
ny=c-1
 
xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))
 
V=[[0]*(nx+1+1) for i in range(ny+1+1)]
U=[i[:]for i in V]

for (a,b),c in R:
    U[ydcr[c]][xdcr[a]]+=1
    U[ydcr[c]][xdcr[b]]+=-1
for i in range(ny+1):
    for j in range(nx):
        U[i][j+1]+=U[i][j]
        
for d,(e,f) in H:
    V[ydcr[e]][xdcr[d]]+=1
    V[ydcr[f]][xdcr[d]]+=-1
for j in range(nx+1):
    for i in range(ny):
        V[i+1][j]+=V[i][j]

v=[[0]*(nx+1) for i in range(ny+1)]
q=[(xdcr[0],ydcr[0])]
v[ydcr[0]][xdcr[0]]=1

a=0
while q:
    
    cx,cy=q.pop()
    a+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1])
    for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]:
        k=0
        nbx=cx+dx
        nby=cy+dy
        if (0>nbx>=nx)or(0>nby>=ny)or v[nby][nbx]==1:
            continue
        if dy!=0:
            k=U[-~dy//2+cy][cx]==0
        else:
            k=V[cy][-~dx//2+cx]==0
        if k:
            q.append((nbx,nby));v[nby][nbx]=1
if a>=F:a='F'
print(a)

Submission status: Wrong Answer

Solution code:
from collections import*
LI=lambda:[int(i)for i in input().split()]

F=1<<65
n,m=LI()
Z=[set(),set()]
X=set([0,F,-F])
Y=set(X)
V=[]
H=[]
for i in range(n):
    a,b,c=LI()
    V.append(((a,b),c))
    Y.add(c)
    X.add(a)
    X.add(b)
 
n+=2
V.append(((-F,F),F))
V.append(((-F,F),-F))
 
for i in range(m):
    a,b,c=LI()
    H.append(((b,c),a))
    X.add(a)
    Y.add(b)
    Y.add(c)
 
m+=2
H.append(((-F,F),F))
H.append(((-F,F),-F))


xdc=dict(enumerate(sorted(X)));nx=len(xdc)
ydc=dict(enumerate(sorted(Y)));ny=len(ydc)

xdcr={j:i for i,j in xdc.items()}
ydcr={j:i for i,j in ydc.items()}

mpy=[[0]*-~nx for i in range(ny+1)]
mpx=[i[:]for i in mpy]

for (a,b),c in V:
    mpx[ydcr[c]][xdcr[a]]+=1
    mpx[ydcr[c]][xdcr[b]]+=-1
for i in range(ny+1):
    for j in range(nx):
        mpx[i][j+1]+=mpx[i][j]
        
for (e,f),d in H:
    mpy[ydcr[e]][xdcr[d]]+=1
    mpy[ydcr[f]][xdcr[d]]+=-1
for j in range(nx+1):
    for i in range(ny):
        mpy[i+1][j]+=mpy[i][j]

v=[[0]*-~nx for i in range(ny+1)]
q=deque([(xdcr[0],ydcr[0])])
v[ydcr[0]][xdcr[0]]=1

a=0
while q:
    cx,cy=q.popleft()
    a+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1])
    for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]:
        nbx=cx+dx
        nby=cy+dy
        if (not 0<=nbx<nx) or (not 0<=nby<ny) or v[nby][nbx]==1:
            continue
        if dy!=0:
            if mpx[cy-~dy//2][cx]==0:
                q.append((nbx,nby))
                v[nby][nbx]=1
        else:
            if mpy[cy][cx-~dx//2]==0:
                q.append((nbx,nby))
                v[nby][nbx]=1
if a>=F:a='F'
print(a)

Submission status: Wrong Answer

Solution code:
from collections import*
LI=lambda:[int(i)for i in input().split()]

F=1<<65
n,m=LI()
X=set([0,F,-F])
Y=set(X)
V=[]
H=[]
for i in range(n):
    a,b,c=LI()
    V.append(((a,b),c))
    Y.add(c)
    X.add(a)
    X.add(b)
 
n+=2
V.append(((-F,F),F))
V.append(((-F,F),-F))
 
for i in range(m):
    a,b,c=LI()
    H.append(((b,c),a))
    X.add(a)
    Y.add(b)
    Y.add(c)
 
m+=2
H.append(((-F,F),F))
H.append(((-F,F),-F))


xdc=dict(enumerate(sorted(X)));nx=len(xdc)
ydc=dict(enumerate(sorted(Y)));ny=len(ydc)

xdcr={j:i for i,j in xdc.items()}
ydcr={j:i for i,j in ydc.items()}

mpy=[[0]*-~nx for i in range(ny+1)]
mpx=[i[:]for i in mpy]

for (a,b),c in V:
    mpx[ydcr[c]][xdcr[a]]+=1
    mpx[ydcr[c]][xdcr[b]]+=-1
for i in range(ny+1):
    for j in range(nx):
        mpx[i][j+1]+=mpx[i][j]
        
for (e,f),d in H:
    mpy[ydcr[e]][xdcr[d]]+=1
    mpy[ydcr[f]][xdcr[d]]+=-1
for j in range(nx+1):
    for i in range(ny):
        mpy[i+1][j]+=mpy[i][j]

v=[[0]*-~nx for i in range(ny+1)]
q=[(xdcr[0],ydcr[0])]
v[ydcr[0]][xdcr[0]]=1

a=0
while q:
    cx,cy=q.pop()
    a+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1])
    for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]:
        nbx=cx+dx
        nby=cy+dy
        if (not 0<=nbx<nx) or (not 0<=nby<ny) or v[nby][nbx]==1:
            continue
        if dy!=0:
            if mpx[cy-~dy//2][cx]==0:
                q.append((nbx,nby))
                v[nby][nbx]=1
        else:
            if mpy[cy][cx-~dx//2]==0:
                q.append((nbx,nby))
                v[nby][nbx]=1
if a>=F:a='F'
print(a)

Submission status: Wrong Answer

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
 
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def __str__(self):
        return  str(self.edges)
 
    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)
 
class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]
 
    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

def dijkstra(edge,st):
    # edge=[[(v_to,dist_to_v),...],[],...]
    # initialize: def: d=dist(st,i), prev=[previous vertex in minimum path], q[]
    n=len(edge)
    d=[(0 if st==i else inf) for i in range(n)]
    prev=[0]*n
    q=[(j,i) for i,j in enumerate(d)]
    heapify(q)
    v=[False]*n
    # calc
    while q:
        dist,cur=heappop(q)
        if v[cur]:
            continue
        v[cur]=True
        for dst,dist in edge[cur]:
            alt=d[cur]+dist
            if alt<d[dst]:
                d[dst]=alt
                prev[dst]=cur
                heappush(q,(alt,dst))
    return d,prev


show_flg=False
show_flg=True
ans=0
inf=1<<65
n,m=LI()
X=[0,inf,-inf]
Y=[0,inf,-inf]
V=[]
H=[]
for i in range(n):
    a,b,c=LI()
    V.append(((a,b),c))
    Y.append(c)
    X.append(a)
    X.append(b)
 
n+=2
V.append(((-inf,inf),inf))
V.append(((-inf,inf),-inf))
 
for i in range(m):
    a,b,c=LI()
    H.append((a,(b,c)))
    X.append(a)
    Y.append(b)
    Y.append(c)
 
m+=2
H.append((inf,(-inf,inf)))
H.append((-inf,(-inf,inf)))
 
 
X.sort()
xdc={}
c=1
for j in sorted(set(X)):
    xdc[c]=j
    c+=1
nx=c-1
 
Y.sort()
ydc={}
c=1
for j in sorted(set(Y)):
    ydc[c]=j
    c+=1
ny=c-1
 
xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))
 
mpy=[[0]*(nx+1+1) for i in range(ny+1+1)]
mpx=[[0]*(nx+1+1) for i in range(ny+1+1)]
#mpy=[[0]*(2*nx+2) for i in range(2*ny+2)]
 
for (a,b),c in V:
    mpx[ydcr[c]][xdcr[a]]+=1
    mpx[ydcr[c]][xdcr[b]+1]+=-1
for i in range(ny+1):
    for j in range(nx):
        mpx[i][j+1]+=mpx[i][j]
        
for d,(e,f) in H:
    mpy[ydcr[e]][xdcr[d]]+=1
    mpy[ydcr[f]+1][xdcr[d]]+=-1
for j in range(nx+1):
    for i in range(ny):
        mpy[i+1][j]+=mpy[i][j]
 
for i in mpx:
    show(i)
show()
for i in mpy:
    show(i)
exit()

v=[[0]*(nx+1) for i in range(ny+1)]
q=deque()
q.append((xdcr[0],ydcr[0]))
v[ydcr[0]][xdcr[0]]=1
while q:
    cx,cy=q.popleft()
    px,py=cx>>1,cy>>1
    
    ans+=(xdc[px]-xdc[px+1])*(ydc[py]-ydc[py+1])
    #show((cx,cy),(xdc[px]-xdc[px-1])*(ydc[py]-ydc[py-1]),(xdc[px],xdc[px-1]),(ydc[py],ydc[py-1]))
    #show((cx,cy),px,py)
    for dx,dy in FourNb:
        nbx=cx+dx
        nby=cy+dy
        if (not 0<=nbx<nx) or (not 0<=nby<ny) or v[nby][nbx]==1:
            continue
        
        if mpx[nby-dy][nbx-dx]==0:
            q.append((nbx,nby))
            v[nby][nbx]=1
 
if ans>=inf:
    ans='INF'
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from itertools import chain


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

def input_row(n : int, type=np.int, **kwargs):
	return np.fromiter(inputs(type, **kwargs), dtype=type)

def input_2d(nrows : int, ncols : int, type=np.int, **kwargs):
	data = np.fromiter(
		chain.from_iterable(
			inputs(type) for _ in range(nrows)
		),
		dtype=type
	)
	return data.reshape(nrows, ncols)

from collections import deque
import numpy as np


N, M = inputs(int)
A, B, C = input_2d(N, 3).T
D, E, F = input_2d(M, 3).T
xs = np.unique(C)
ys = np.unique(D)

x_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)
y_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

C = np.searchsorted(xs, C, side='right')
A = np.searchsorted(ys, A, side='right')
B = np.searchsorted(ys, B, side='right')

D = np.searchsorted(ys, D, side='right')
E = np.searchsorted(xs, E, side='right')
F = np.searchsorted(xs, F, side='right')

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

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

cow = (
	np.searchsorted(xs, 0, side='right'),
	np.searchsorted(ys, 0, side='right')
)
nexts = deque([cow])
visited = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)
visited[cow] = True

area = 0

while nexts:
	xi, yi = nexts.popleft()
	
	if 0 < xi < len(xs) and 0 < yi < len(ys):
		area += (xs[xi] - xs[xi-1]) * (ys[yi] - ys[yi-1])
		if not visited[xi-1, yi] and not x_guard[xi, yi]:
			visited[xi-1, yi] = True
			nexts.append((xi-1, yi))
		if not visited[xi+1, yi] and not x_guard[xi+1, yi]:
			visited[xi+1, yi] = True
			nexts.append((xi+1, yi))
		if not visited[xi, yi-1] and not y_guard[xi, yi]:
			visited[xi, yi-1] = True
			nexts.append((xi, yi-1))
		if not visited[xi, yi+1] and not y_guard[xi, yi+1]:
			visited[xi, yi+1] = True
			nexts.append((xi, yi+1))
	else:
		area = 'INF'
		break

print(area)

Submission status: Wrong Answer

Solution code:
from collections import deque
from itertools import product
import sys
n, m = map(int, input().split())
vertical = list()
horizontal = list()
for _ in range(n):
  a, b, c = map(int, input().split())
  vertical.append((a, b, c))
for _ in range(m):
  d, e, f = map(int, input().split())
  horizontal.append((d, e, f))
leftmost = sys.maxsize
rightmost = -sys.maxsize
for segment in vertical:
  leftmost = min(segment[2], leftmost)
  rightmost = max(segment[2], rightmost)
upmost = sys.maxsize
downmost = -sys.maxsize
for segment in horizontal:
  upmost = min(segment[0], upmost)
  downmost = max(segment[0], downmost)
# maybe bfs... integer grid may be too fine.
stack_positions = deque()
covered_positions = set()
# true position is -0.5, -0.5 of this
initial_range = [0, 1]
for d, r in product(initial_range, initial_range):
  stack_positions.append((d, r))
  covered_positions.add((d, r))
area = 4
d, r = 0, 0
while upmost-3<=d<=downmost and leftmost-3<=r<=3+rightmost and stack_positions:
  d, r = stack_positions.popleft()
  can_go_right = True
  can_go_left = True
  can_go_up = True
  can_go_down = True
  for segment in vertical:
    if r == segment[2]:
      if segment[0]<d<=segment[1]: can_go_right = False
    elif r == segment[2]+1:
      if segment[0]<d<=segment[1]: can_go_left = False
  for segment in horizontal:
    if d == segment[0]:
      if segment[1]<r<=segment[2]: can_go_down = False
    elif d == segment[0]+1:
      if segment[1]<r<=segment[2]: can_go_up = False
  can_go_right = can_go_right and not (r+1, d) in covered_positions
  can_go_left = can_go_left and not (r-1, d) in covered_positions
  can_go_down = can_go_down and not (r, d+1) in covered_positions
  can_go_up = can_go_up and not (r, d-1) in covered_positions
  if can_go_right:
    area += 1
    stack_positions.append((r+1, d))
    covered_positions.add((r+1, d))
  if can_go_left:
    area += 1
    stack_positions.append((r-1, d))
    covered_positions.add((r-1, d))
  if can_go_up:
    area += 1
    stack_positions.append((r, d-1))
    covered_positions.add((r, d-1))
  if can_go_down:
    area += 1
    stack_positions.append((r, d+1))
    covered_positions.add((r, d+1))
if not stack_positions:
  print(area)
else:
  print("INF")