Problem:


Score : 600 points

Problem Statement

There is a grid with N rows and N columns of squares. Let (i, j) be the square at the i-th row from the top and the j-th column from the left.

Each of the central (N-2) \times (N-2) squares in the grid has a black stone on it.
Each of the 2N - 1 squares on the bottom side and the right side has a white stone on it.

Q queries are given. We ask you to process them in order.
There are two kinds of queries. Their input format and description are as follows:

1 x: Place a white stone on (1, x). After that, for each black stone between (1, x) and the first white stone you hit if you go down from (1, x), replace it with a white stone.

2 x: Place a white stone on (x, 1). After that, for each black stone between (x, 1) and the first white stone you hit if you go right from (x, 1), replace it with a white stone.

How many black stones are there on the grid after processing all Q queries?

Constraints

3 \leq N \leq 2\times 10^5

0 \leq Q \leq \min(2N-4,2\times 10^5)

2 \leq x \leq N-1

Queries are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N Q
Query_1
\vdots
Query_Q

Output

Print how many black stones there are on the grid after processing all Q queries.

Sample Input 1

5 5
1 3
2 3
1 4
2 2
1 2

Sample Output 1

1

After each query, the grid changes in the following way:

Sample Input 2

200000 0

Sample Output 2

39999200004

Sample Input 3

176527 15
1 81279
2 22308
2 133061
1 80744
2 44603
1 170938
2 139754
2 15220
1 172794
1 159290
2 156968
1 56426
2 77429
1 97459
2 71282

Sample Output 3

31159505795



Sample input:
5 5
1 3
2 3
1 4
2 2
1 2


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())

black = pow(N-2, 2)
right = [N for _ in range(N-2)]
bottom = [N for _ in range(N-2)]
left = N-1
top = N-1

for i in range(Q):
    q, x = list(map(int, input().split()))
    if q == 1:
        black -= (bottom[x-2] -2)
        if x > left:
            continue
        left = x
        for y in range(bottom[x-2]-2):
            right[y] = x
    else:
        black -= (right[x-2] -2)
        if x > top:
            continue
        top = x
        for y in range(right[x-2]-2):
            bottom[y] = x

print(black)

Submission status: Time Limit Exceeded

Solution code:
class segtree():
    def segfunc(x,y):
        return min(x,y)
    #####単位元######
    ide_ele = -1
    n=1
    init_val=[0]*n
    #num:n以上の最小の2のべき乗
    num =2**(n-1).bit_length()
    seg=[ide_ele]*2*num
    
    def __init__(self,INIT_VAL,SEGFUNC,IDE_ELE):
        self.ide_ele=IDE_ELE
        self.init_val=[i for i in INIT_VAL]
        self.segfunc=SEGFUNC
        self.n=len(self.init_val)
        self.num =2**(self.n-1).bit_length()
        self.seg=[self.ide_ele]*2*self.num
 
        #set_val
        for i in range(self.n):
            self.seg[i+self.num-1]=self.init_val[i]    
        #built
        for i in range(self.num-2,-1,-1) :
            self.seg[i]=self.segfunc(self.seg[2*i+1],self.seg[2*i+2]) 
        
    def update(self,k,x):
        k += self.num-1
        self.seg[k] = x
        while k+1:
            k = (k-1)//2
            self.seg[k] = self.segfunc(self.seg[k*2+1],self.seg[k*2+2])
        
    def query(self,p,q):
        if q<=p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res=self.ide_ele
        while q-p>1:
            if p&1 == 0:
                res = self.segfunc(res,self.seg[p])
            if q&1 == 1:
                res = self.segfunc(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfunc(res,self.seg[p])
        else:
            res = self.segfunc(self.segfunc(res,self.seg[p]),self.seg[q])
        return res

N,Q=map(int,input().split())
X=segtree([0 for i in range(N)],(lambda x,y:x+y),0)
Y=segtree([0 for i in range(N)],(lambda x,y:x+y),0)
ans=(N-2)*(N-2)
for i in range(Q):
    k,x=map(int,input().split())
    #print(i,ans)
    #print([X.query(0,i) for i in range(1,N)],[Y.query(0,i) for i in range(1,N)])
    dp=[[-1 for i in range(N)] for i in range(N)]
    for i in range(1,N):
        dp[-i-1][-1]=Y.query(0,i)
        dp[-1][-1-i]=X.query(0,i)
    x=N-x+1
    #for line in dp:
    #    print(line)
        
    if k==1:
        a=X.query(0,x)
        ans-=N-2-a
        if Y.query(a,a+1)<x-1:
            Y.update(a,x-1)
    else:
        b=Y.query(0,x)
        ans-=N-2-b
        if X.query(b,b+1)<x-1:
            X.update(b,x-1)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
f=lambda:map(int,input().split())
N,Q=f()
a,b=N,N
black=(N-2)*(N-2)
B=[-1]*(N+1)
W=[-1]*(N+1)
for _ in range(Q):
    q,x=f()
    if q==1:
        if B[x]>0:
            black-=B[x]
            B[x]=0
        else:
            black-=b-2
            a=x
            for j in range(a+1,N+1):
                if B[j]==-1:
                    B[j]=b-2
                if j==N-1:
                    break
    else:
        if W[x]>0:
            black-=W[x]
            W[x]=0
        else:
            black-=a-2
            b=x
            for j in range(b+1,N+1):
                if W[j]==-1:
                    W[j]=a-2
                else:
                    break
                if j==N-1:
                    break
print(black)

Submission status: Time Limit Exceeded

Solution code:
f=lambda:map(int,input().split())
N,Q=f()
a,b=N,N
black=(N-2)*(N-2)
B=[-1]*(N+1)
W=[-1]*(N+1)
for _ in range(Q):
    q,x=f()
    if q==1:
        if B[x]>0:
            black-=B[x]
            B[x]=0
        else:
            black-=b-2
            a=x
            for j in range(a+1,N+1):
                if B[j]==-1:
                    B[j]=b-2
                if j==N-1:
                    break
    else:
        if W[x]>0:
            black-=W[x]
            W[x]=0
        else:
            black-=a-2
            b=x
            for j in range(b+1,N+1):
                if W[j]==-1:
                    W[j]=a-2
                if j==N-1:
                    break
print(black)

Submission status: Time Limit Exceeded

Solution code:
ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(map(int, input().split()))

n, q = li()

col = [n-1] * n
row = [n-1] * n
ans = (n-2)*(n-2)
for i in range(q):
    k, x = li()
    if(k == 1):
        ans -= col[x-1]-1
        col[x-1] = 1
        for j, r in enumerate(row):
            if(row[j] <= x-1):
                break
            row[j] = x-1
    if(k == 2):
        ans -= row[x-1]-1
        row[x-1] = 1
        for j, r in enumerate(col):
            if(col[j] <= x-1):
                break
            col[j] = x-1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq

n, q = map(int, input().split())
'''
row, col =[n], [n]
ans = (n-2)**2

for i in range(q):
    order, x = map(int, input().split())
    if order == 1:
        heapq.heappush(col, x)
        ans -= row[0]-2
    else:
        heapq.heappush(row, x)
        ans -= col[0]-2
    print(ans)
print(ans)
'''

row = [n for _ in range(n+1)]
col = [n for _ in range(n+1)]
row[0], col[0] = 0, 0
row[-1], col[-1] = 1, 1
ans = (n-2)**2

for i in range(q):
    o, x = map(int, input().split())
    if o == 1:
        t = col[x]
        col[x] = 1
        ans -= t-2
        for j in range(t):
            row[j] = min(row[j], x)
    else:
        t = row[x]
        row[x] = 1
        ans -= t-2
        for j in range(t):
            col[j] = min(col[j], x)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,Q=map(int,input().split())
a=[N-2 for _ in range(N-2)]
b=[N-2 for _ in range(N-2)]
black=(N-2)**2
for _ in range(Q):
    t,l=map(int,input().split())
    if t==1:
        black -= a[l-2]
        for i in range(a[l-2]):
            b[i] = min(b[i],l - 2)
    elif t==2:
        black -= b[l-2]
        for i in range(b[l-2]):
            a[i] = min(a[i],l - 2)
print(black)

Submission status: Time Limit Exceeded

Solution code:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())

def resolve():
    N, Q = iim()
    it = map(int, sys.stdin.read().split())

    N2 = N - 2
    cc = [N-1] * 2
    ans = (N-2)**2
    A = [[N2]*(N2) for i in range(2)]

    for q, i in zip(it, it):
        q -= 1; i -= 2
        #print(q, i, N2)
        val = A[q][i]
        ans -= val
        aa = A[q^1]
        for j in range(val):
            aa[j] = min(aa[j], i)
        #print(ans, A)
    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int,input().split())
gyo = [N] * (N-2)
retu = [N] * (N-2)
ans = (N-2)**2
min_gyo = N
min_retu = N
for i in range(Q):
    a, b = map(int,input().split())
    if a == 1:
        x = retu[b-2]
        if min_gyo > b:
            for j in range(x-2):
                gyo[j] = b
            #gyo = [b]*(x-2) + gyo[x-2:N-2]
            min_gyo = b
        ans = ans - (x-2)
    else:
        x = gyo[b-2]
        if min_retu > b:
            for j in range(x-2):
                retu[j] = b
            #retu = [b]*(x-2) + retu[x-2:N-2]
            min_retu = b
        ans = ans - (x-2)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, Counter, defaultdict
from itertools import chain, combinations
import json
# import numpy as np
import bisect
import sys
import math
import bisect
from functools import lru_cache
import itertools

sys.setrecursionlimit(10 ** 8)

M = 10 ** 9 + 7
INF = 10 ** 17


def main():
    # N = int(input())
    N, Q = [int(a) for a in input().split()]
    Querys = [
        [int(a) for a in input().split()]
        for _ in range(Q)
    ]

    tate_k = []  # 縦消しの長さ
    tate_v = []  # その縦消しの左からの距離
    yoko_k = []
    yoko_v = []

    def get_l(k, v, x):
        if len(k) == 0:
            return N - 2
        index = bisect.bisect_left(k, x)
        if index == len(k):
            return N - 2
        return v[index]

    # blocked = []
    # current_type = None
    # current_block = []
    # for qtype, x in Querys:
    #     if current_type == qtype:
    #         current_block.append(x)
    #         continue
    #     current_type = qtype
    #     if len(current_block) != 0:
    #         blocked.append(current_block)
    #     current_block = [x]
    # if len(current_block) != 0:
    #     blocked.append(current_block)

    # print(blocked)
    total = 0
    for qtype, x in Querys:
        if qtype == 1:
            length = get_l(tate_k, tate_v, x)
            total += length
            length += 1
            ii = bisect.bisect_left(yoko_k, length)
            yoko_k.insert(ii, length)
            x -= 2
            ii = bisect.bisect_left(yoko_v, x)
            yoko_v.insert(ii, x)
        else:
            length = get_l(yoko_k, yoko_v, x)
            total += length
            length += 1
            ii = bisect.bisect_left(tate_k, length)
            tate_k.insert(ii, length)
            x -= 2
            ii = bisect.bisect_left(tate_v, x)
            tate_v.insert(ii, x)

    print((N - 2) * (N - 2) - total)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())
dpU = [N]*N
dpL = [N]*N
ans = (N-2)**2

for _ in range(Q):
    cmd, x = map(int, input().split())
    if cmd == 1:
        ans -= dpU[x]-2
        for i in range(2, dpU[x]):
            dpL[i] = min(dpL[i], x)
        dpU[x] = 1
    else:
        ans -= dpL[x]-2
        for i in range(2, dpL[x]):
            dpU[i] = min(dpU[i], x)
        dpL[x] = 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, Q = list(map(int, input().split()))

tate = [(N - 2)] * (N - 2)
yoko = [(N - 2)] * (N - 2)

black = (N-2)*(N-2)

for i in range(Q):
    type, x = list(map(int, input().split()))
    x = x - 2
    if (type == 1):
        black = black - tate[x]

        yoko[:tate[x]] = [min(yoko[j], x) for j in range(tate[x])]

        tate[x] = 0

    else:
        black = black - yoko[x]

        tate[:yoko[x]] = [min(tate[j], x) for j in range(yoko[x])]
        yoko[x] = 0


print(black)

Submission status: Time Limit Exceeded

Solution code:
n,q = list(map(int,input().split()))
res = (n-2)**2
lx = [n-1 for _ in range(n)]
ly = [n-1 for _ in range(n)]
for _ in range(q):
  q1,q2 =  list(map(int,input().split()))
  q2-=1
  if q1 == 1:
    res -= (lx[q2]-1)
    for i in range(1,lx[q2]):
      if ly[i] >= q2:
        ly[i] = q2
  else:
    res -= (ly[q2]-1)
    for i in range(1,ly[q2]):
      if lx[i] >= q2:
        lx[i] = q2
print(res)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    # sys.setrecursionlimit = 10 ** 7
    input = sys.stdin.readline

    n, q = map(int, input().split())

    rows = [n - 1] * n
    cols = [n - 1] * n

    ans = (n - 2) * (n - 2)
    for _ in range(q):
        t, x = input().rstrip().split()
        x = int(x) - 1
        if t == '1':
            # (0,x)にW
            ans -= cols[x] - 1
            for j in range(cols[x]):
                rows[j] = min(rows[j], x)
            cols[x] = 1
        else:
            # (x,0)にW
            ans -= rows[x] - 1
            for j in range(rows[x]):
                cols[j] = min(cols[j], x)
            rows[x] = 1

    print(ans)


if __name__ == '__main__':
    main()

# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,Q = map(int,input().split())
C = [N]*N
R = [N]*N

ans = (N-2)**2
for _ in range(Q):
    n,x = map(int,input().split())
    if n == 1:
#        print(1,x)
        ans -= C[x-1]-2
        if x<R[0]:
            for i in range(C[x-1]):
                R[i] = x
    if n == 2:
#        print(x,1)
        ans -= R[x-1]-2
        if x<C[0]:
            for i in range(R[x-1]):
                C[i] = x
#    print(C)
#    print(R)
#    print("ans",ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int,input().split())
gyo = [N] * (N-2)
retu = [N] * (N-2)
ans = (N-2)**2
min_gyo = N
min_retu = N
for i in range(Q):
    a, b = map(int,input().split())
    if a == 1:
        x = retu[b-2]
        if min_gyo > b:
            gyo = [b]*(x-2) + gyo[x-2:N-2]
            min_gyo = b
        ans = ans - (x-2)
    else:
        x = gyo[b-2]
        if min_retu > b:
            retu = [b]*(x-2) + retu[x-2:N-2]
            min_retu = b
        ans = ans - (x-2)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,Q = map(int,input().split())
C = [N]*N
R = [N]*N

ans = (N-2)**2
for _ in range(Q):
    n,x = map(int,input().split())
    if n == 1:
#        print(1,x)
        ans -= C[x-1]-2
        if x<R[0]:
            for i in range(C[x-1]):
                R[i] = x
    if n == 2:
#        print(x,1)
        ans -= R[x-1]-2
        if x<C[0]:
            for i in range(R[x-1]):
                C[i] = min(C[i],x)
#    print(C)
#    print(R)
#    print("ans",ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, q = list(map(int, input().split()))
count = (n - 2) ** 2
c = [n] * n
r = [n] * n
for _ in range(q):
  m,q = list(map(int, input().split()))
  if m == 1:
    pos = r[q-1]
    c[:pos] = [min(q, v) for v in c[:pos]] 
    r[q-1] = 1
    if q not in [1,n]:
      count -= max(0, pos - 2)
  else:
    pos = c[q-1]
    r[:pos] = [min(q, v) for v in r[:pos]]
    c[q-1] = 1
    if q not in [1,n]:
      count -= max(0, pos-2)
print(count)

Submission status: Time Limit Exceeded

Solution code:

def main():
    N , Q = map(int, input().split())
    query = [tuple(map(int, input().split())) for _ in range(Q)]
    replace = {0:[N-2] * (N-2), 1:[N-2] * (N-2)}
    replaced = 0
    for i, x in query:
        i += -1
        replaced += replace[i][x-2]
        for j in range(replace[i][x-2]):
            replace[i^1][j] = min(replace[i^1][j], x-2)
    print((N-2)**2 - replaced)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

N,Q=map(int,input().split())

seg_el=1<<((N+1).bit_length()) # Segment treeの台の要素数

SEG=[N-2]*(2*seg_el) # 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化
SEG2=[N-2]*(2*seg_el)

def getvalue(n,seg_el): # 一点の値を取得
    i=n+seg_el
    ANS=N-2
    
    ANS=min(SEG[i],ANS)
    i>>=1# 子ノードへ
    
    while i!=0:
        ANS=min(SEG[i],ANS)
        i>>=1

    return ANS

def getvalue2(n,seg_el): # 一点の値を取得
    i=n+seg_el
    ANS=N-2
    
    ANS=min(SEG2[i],ANS)
    i>>=1# 子ノードへ
    
    while i!=0:
        ANS=min(SEG2[i],ANS)
        i>>=1

    return ANS

def updates(l,r,x): # 区間[l,r)のminを更新.
    L=l+seg_el
    R=r+seg_el

    while L<R:
        if L & 1:
            SEG[L]=min(x,SEG[L])
            L+=1

        if R & 1:
            R-=1
            SEG[R]=min(x,SEG[R])
        L>>=1
        R>>=1

def updates2(l,r,x): # 区間[l,r)のminを更新.
    L=l+seg_el
    R=r+seg_el

    while L<R:
        if L & 1:
            SEG2[L]=min(x,SEG2[L])
            L+=1

        if R & 1:
            R-=1
            SEG2[R]=min(x,SEG2[R])
        L>>=1
        R>>=1

ANS=(N-2)*(N-2)

MINX=N
MINY=N

for queries in range(Q):
    t,x=map(int,input().split())

    if t==1:
        v=getvalue(x,seg_el)
        ANS-=v
        updates2(1,MINY,x-2)
        MINX=min(MINX,x)

    else:
        v=getvalue2(x,seg_el)
        ANS-=v
        updates(1,MINX,x-2)
        MINY=min(MINY,x)

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
n, q = list(map(int, input().split()))
count = (n - 2) ** 2
c = [n] * n
r = [n] * n
for _ in range(q):
  m,q = list(map(int, input().split()))
  if m == 1:
    pos = r[q-1]
    c[:pos] = [min(q, v) for v in c[:pos]] 
    r[q-1] = 1
    if q not in [1,n]:
    	count -= max(0, pos - 2)
  else:
    pos = c[q-1]
    r[:pos] = [min(q, v) for v in r[:pos]]
    c[q-1] = 1
    if q not in [1,n]:
   		count -= max(0, pos-2)
print(count)

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int,input().split())
C = [N]*N
R = [N]*N

ans = (N-2)**2
for _ in range(Q):
    n,x = map(int,input().split())
    if n == 1:
#        print(1,x)
        ans -= C[x-1]-2
        for i in range(C[x-1]):
            R[i] = min(R[i],x)
    if n == 2:
#        print(x,1)
        ans -= R[x-1]-2
        for i in range(R[x-1]):
            C[i] = min(C[i],x)
#    print(C)
#    print(R)
#    print("ans",ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:

def main():
    N , Q = map(int, input().split())
    replace = {0:[N-2] * (N-2), 1:[N-2] * (N-2)}
    replaced = 0
    for _ in range(Q):
        i, x = map(int, input().split())
        i += -1
        replaced += replace[i][x-2]
        for j in range(replace[i][x-2]):
            replace[i^1][j] = min(replace[i^1][j], x-2)
    print((N-2)**2 - replaced)

main()

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left as bl

N, Q = map(int, input().split())
ans = 0
q1 = []
q2 = []
query = []
for _ in range(Q):
    n, p = map(int, input().split())
    query.append((n, p))
    if n == 1:
        q1.append(p)
    else:
        q2.append(p)
q1.sort()
q2.sort()
board = [N - 2, N - 2]
for n, p in query:
    if n == 1:
        if p > board[1] + 1:
            continue
        index = bl(q1, p)
        ans += board[0] * (len(q1) - index)
        board[1] = p - 2
        q1 = q1[:index]
    else:
        if p > board[0] + 1:
            continue
        index = bl(q2, p)
        ans += board[1] * (len(q2) - index)
        board[0] = p - 2
        q2 = q2[:index]
print((N - 2) ** 2 - ans)

Submission status: Time Limit Exceeded

Solution code:
## coding: UTF-8
N, Q = map(int,input().split())
lq = [list(map(int, input().split())) for _ in range(Q)]

#print(N, Q, lq)


now = (N-2) * (N-2)

tate = ['a'] + [N] * (N-2) + [1]
yoko = ['a'] + [N] * (N-2) + [1]

#print(tate, yoko, now)


for i in range(Q):
    query = lq[i]
    if(query[0] == 1):
        heru = tate[query[1]-1] - 2
        tate[query[1]-1] = 1
        now -= heru
        for j in range(1, heru + 1):
            yoko[j] = min(yoko[j], query[1])
    else:
        heru = yoko[query[1]-1] - 2
        yoko[query[1]-1] = 1
        now -= heru
        for j in range(1, heru + 1):
            tate[j] = min(tate[j], query[1])
    #print(query, tate, yoko, now)
print(now)



'''
#2~N列目において、最も上にある白い石の行数を記録（最初はN行目）
tate = ['a', 'a'] + [N] * (N-2)

#2~N行目において、最も左にある白い石の列数を記録（最初はN列目）
yoko = ['a', 'a'] + [N] * (N-2)

for i in range(Q):
    query = lq[i]
    if(query[0] == 1):
        #縦に白い石が増える
        heru = tate[query[1]] - 2
        tate[query[1]] = 0
        now -= heru
        for _ in range(2, N):
            yoko[_] = min(yoko[_], query[1])
    else:
        #横に白い石が増える
        heru = yoko[query[1]] - 2
        yoko[query[1]] = 0
        now -= heru
        for _ in range(2, N):
            tate[_] = min(tate[_], query[1])
    print(query, tate, yoko, now)
print(now)
'''

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())
ans = (N-2)*(N-2)
R = [N]*(N+1)
W = [N]*(N+1)
for i in range(Q):
    a, b = map(int, input().split())
    if a == 1:
        ans -= max(0, R[b] - 2)
        if b <= W[1]:
            for j in range(1, R[b]+1):
                W[j] = b
        R[b] = 0
    else:
        ans -= max(0, W[b] - 2)
        if b <= R[1]:
            for j in range(1, W[b] + 1):
                R[j] = b
        W[b] = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, Q = list(map(int, input().split()))

tate = [(N - 2)] * (N - 2)
yoko = [(N - 2)] * (N - 2)

black = (N-2)*(N-2)

for i in range(Q):
    type, x = list(map(int, input().split()))
    x = x - 2
    if (type == 1):
        black = black - tate[x]

        replace = [min(yoko[j], x) for j in range(tate[x])]
        yoko[:tate[x]] = replace

        tate[x] = 0

    else:
        black = black - yoko[x]

        replace = [min(tate[j], x) for j in range(yoko[x])]
        tate[:yoko[x]] = replace
        yoko[x] = 0


print(black)

Submission status: Time Limit Exceeded

Solution code:
import bisect
N,Q = map(int, input().split())
L = [0]*Q
L1 = []
L2 = []
for i in range(Q):
    a,b = map(int, input().split())
    L[i] = (a, b)
    if a == 1:
        L1.append(b)
    else:
        L2.append(b)

L1.sort()
L2.sort()

ans = (N-2)**2
up = N
left = N
for l in L:
    a = l[0]
    b = l[1]
    if a == 1:
        if b > left:
            continue
        idx = bisect.bisect_left(L1, b)
        ans -= (len(L1)-idx)*(up-2)
        L1 = L1[:idx]
        left = b
    else:
        if b > up:
            continue
        idx = bisect.bisect_left(L2, b)
        ans -= (len(L2)-idx)*(left-2)
        L2 = L2[:idx]
        up = b
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int, input().split())
q = [list(map(int, input().split())) for _i in range(q)]

x_list = [n-1]*n
y_list = [n-1]*n
res = (n-2)**2

from bisect import bisect_right
for i, j in q:
    j -= 1
    if i==1:
        position = x_list[j]
        res -= position-1
        for s in range(1, position):
            y_list[s] = min(y_list[s], j)
    else:
        position = y_list[j]
        res -= position-1
        for s in range(1, position):
            x_list[s] = min(x_list[s], j)
print(res)

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left as bl

N, Q = map(int, input().split())
ans = 0
q1 = []
q2 = []
query = []
for _ in range(Q):
    n, p = map(int, input().split())
    query.append((n, p))
    if n == 1:
        q1.append(p)
    else:
        q2.append(p)
q1s = sorted(q1)
q2s = sorted(q2)
board = [N - 2, N - 2]
for n, p in query:
    if n == 1:
        if p > board[1] + 1:
            continue
        index = bl(q1s, p)
        ans += board[0] * (len(q1s) - index)
        board[1] = p - 2
        q1s = q1s[:index]
    else:
        if p > board[0] + 1:
            continue
        index = bl(q2s, p)
        ans += board[1] * (len(q2s) - index)
        board[0] = p - 2
        q2s = q2s[:index]
print((N - 2) ** 2 - ans)

Submission status: Time Limit Exceeded

Solution code:
N, Q = list(map(int, input().split()))
row = [N-1]*(N-1)
col = [N-1]*(N-1)
ans = (N-2)**2
for _ in range(Q):
    Q_type, x = input().split()
    x = int(x)-1
    if Q_type == '1':
        ans -= row[x] - 1
        for i in range(row[x]):
            col[i] = min(col[i], x)
        row[x] = 0
    else:
        ans -= col[x] - 1
        for i in range(col[x]):
            row[i] = min(row[i], x)
        col[x] = 0
    # print(row)
    # print(col)
    # print(ans, '-----')
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int, input().split())
q = [list(map(int, input().split())) for _i in range(q)]

x_list = [n for _i in range(n+1)]
y_list = [n for _i in range(n+1)]
res = (n-2)**2

from bisect import bisect_right
for i, j in q:
    if i==1:
        position = x_list[j]
        res -= position-2
        for s in range(1, position):
            y_list[s] = min(y_list[s], j)
    else:
        position = y_list[j]
        res -= position-2
        for s in range(1, position):
            x_list[s] = min(x_list[s], j)
print(res)

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())

black = pow(N-2, 2)
right = [N for _ in range(N-2)]
bottom = [N for _ in range(N-2)]
left = N-1
top = N-1

for i in range(Q):
    q, x = list(map(int, input().split()))
    if q == 1:
        black -= (bottom[x-2] -2)
        if x > left:
            continue
        left = x
        for y in range(bottom[x-2]-2):
            right[y] = x
    else:
        black -= (right[x-2] -2)
        if x > top:
            continue
        top = x
        for y in range(right[x-2]-2):
            bottom[y] = x

print(black)

Submission status: Time Limit Exceeded

Solution code:
n,q=map(int,input().split())
l=[[n-2]*(n-2) for x in range(2)]
s=(n-2)*(n-2)
for c in range(q):
    a,b=map(int,input().split())
    a-=1
    b-=2
    if l[1-a][0]>b:
        for d in range(l[a][b]):
            l[1-a][d]=b
    s-=l[a][b]
print(s)

Submission status: Time Limit Exceeded

Solution code:
import sys
import math


def input():
    return sys.stdin.readline().rstrip()


def main():
    N, Q = map(int, input().split())

    U_depth = [N - 2] * (N - 2)
    L_depth = [N - 2] * (N - 2)

    B = (N - 2) * (N - 2)

    for i in range(Q):
        q, x = map(int, input().split())
        x = x - 2
        if q == 1:  # 上側
            B -= U_depth[x]
            for j in range(U_depth[x]):
                L_depth[j] = min(L_depth[j], x)

        else:
            B -= L_depth[x]
            for j in range(L_depth[x]):
                U_depth[j] = min(U_depth[j], x)
    print(B)


if __name__ == "__main__":
    main()

# \n

Submission status: Time Limit Exceeded

Solution code:
n, q = map(int, input().split())
ans = (n - 2) ** 2
y = [n - 1] * n
x = [n - 1] * n
for i in range(q):
    c, p = map(int, input().split())
    p -= 1
    if c == 1:
        ans -= x[p] - 1
        for i in range(x[p]):
            y[i] = min(y[i], p)
        x[p] = 0
    else:
        ans -= y[p] - 1
        for i in range(y[p]):
            x[i] = min(x[i], p)
        y[p] = 0
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from sys import exit
from collections import deque
from copy import deepcopy
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod=MOD):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        if k<0 or n<k:
            return 0
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x,mode='counter'):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    if mode=='counter':
        return C
    S = set([1])
    for k in C:
        T = deepcopy(S)
        for x in T:
            for i in range(1,C[k]+1):
                S.add(x*(k**i))
    if mode=='set':
        return S
    if mode=='list':
        return sorted(list(S))

######################################################

N,Q=mint()
ans=(N-2)*(N-2)
tate1=[N]
tate2={N:N}
yoko1=[N]
yoko2={N:N}
for _ in range(Q):
    key,x=mint()
    if key==1:
        k=bisect_left(tate1,x)
        v=tate1[k]
        masu=tate2[v]
        insort_left(tate1,x)
        tate2[x]=masu
        ans-=masu-2
        l=bisect_left(yoko1,masu)
        val=yoko1[l]
        tmp=yoko2[val]
        yoko2[val]=min(tmp,x)
    else:
        k=bisect_left(yoko1,x)
        v=yoko1[k]
        masu=yoko2[v]
        insort_left(yoko1,x)
        yoko2[x]=masu
        ans-=masu-2
        l=bisect_left(tate1,masu)
        val=tate1[l]
        tmp=tate2[val]
        tate2[val]=min(tmp,x)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, Q = map(int, input().split())

black = pow(N-2, 2)
right = [N for _ in range(N-2)]
bottom = [N for _ in range(N-2)]

for i in range(Q):
    q, x = list(map(int, input().split()))
    if q == 1:
        black -= (bottom[x-2] -2)
        for y in range(bottom[x-2]-2):
            right[y] = min(right[y], x)
    else:
        black -= (right[x-2] -2)
        for y in range(right[x-2]-2):
            bottom[y] = min(bottom[y], x)

print(black)

Submission status: Time Limit Exceeded

Solution code:
N,Q = map(int, input().split())
answer = (N-2)**2

q1 = [(N,N-2)]
q2 = [(N,N-2)]

def binary_search(q,n):
  left = 0
  right = len(q)-1
  while right-left>0:
    index = (left+right)//2
    if q[index][0] < n:
      left = index+1
    else:
      right = index
  return left

for _ in range(Q):
  n,x = map(int, input().split())
  if n == 1:
    index = binary_search(q1[::-1],x)
    q = q1[-index-1]
    answer -= q[1]
    if index == 0:
      q1.append((x,q[1]))
      q2_last = q2[-1]
      q2[-1] = (q2_last[0],x-2)
  if n == 2:
    index = binary_search(q2[::-1],x)
    q = q2[-index-1]
    answer -= q[1]
    if index == 0:
      q2.append((x,q[1]))
      q1_last = q1[-1]
      q1[-1] = (q1_last[0],x-2)
      
print(answer)