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

Solution code:
class LazyPropSegmentTree:
    def __init__(self, a):
        self.padding = float('inf')        
        self.n = len(a)
        self.N = 1 << (self.n-1).bit_length()
        self.seg_data = [self.padding]*(self.N-1) + a + [self.padding]*(self.N-self.n)
        self.lazy = [None] * (2*self.N - 1)
        for i in range(2*self.N-2, 0, -2):
            self.seg_data[(i-1)>>1] = min(self.seg_data[i], self.seg_data[i-1])
    
    def __len__(self):
        return self.n
    
    def indices_generator(self, i, j):
        # [i, j)
        # [idx1, idx2)を部分的に含むインデックスを降順にyieldするジェネレータ
        idx1 = self.N + i
        idx2 = self.N + j
        lm = (idx1 // (idx1 & -idx1)) >> 1
        rm = (idx2 // (idx2 & -idx2)) >> 1
        while 0 < idx1 < idx2:
            if idx2 <= rm:
                yield idx2-1
            if idx1 <= lm:
                yield idx1-1
            idx1 >>= 1
            idx2 >>= 1
        while idx1:
            yield idx1-1
            idx1 >>= 1
    
    def propagate_down(self, indices):
        # 遅延させていた値を伝搬させる
        # indicesは昇順
        for idx in indices:
            v = self.lazy[idx]
            if v is not None:
                idx1, idx2 = 2*idx + 1, 2*idx + 2
                self.lazy[idx1] = self.lazy[idx2] = v
                self.seg_data[idx1] = min(self.seg_data[idx1], v)
                self.seg_data[idx2] = min(self.seg_data[idx2], v)
                self.lazy[idx] = None
    
    def propagate_up(self, indices):
        for idx in indices:
            idx1, idx2 = 2*idx + 1, 2*idx + 2
            self.seg_data[idx] = min(self.seg_data[idx1], self.seg_data[idx2])
    
    def propagate_all(self):
        indices = [i for i in range(self.N-1)]
        self.propagate_down(indices)
        self.propagate_up(indices[::-1])
    
    def update(self, i, j, x):
        *should_prop, = self.indices_generator(i, j)
        self.propagate_down(should_prop[::-1])
        idx1 = self.N - 1 + i
        idx2 = self.N - 2 + j
        while idx1 < idx2 + 1:
            if idx1&1 == 0: # idx1が偶数
                v = min(x, self.seg_data[idx1])
                self.lazy[idx1] = self.seg_data[idx1] = v
            if idx2&1 == 1: # idx2が奇数
                v = min(x, self.seg_data[idx2])
                self.lazy[idx2] = self.seg_data[idx2] = v
            idx1 >>= 1
            idx2 >>= 1
            idx2 -= 1
        self.propagate_up(should_prop)
    
    def query(self, i, j):
        # [i, j)
        *should_prop, = self.indices_generator(i, j)
        self.propagate_down(should_prop[::-1])
        idx1 = self.N - 1 + i
        idx2 = self.N - 2 + j
        result = self.padding
        while idx1 < idx2 + 1:
                if idx1&1 == 0: # idx1が偶数
                    result = min(result, self.seg_data[idx1])
                if idx2&1 == 1: # idx2が奇数
                    result = min(result, self.seg_data[idx2])                
                idx1 >>= 1
                idx2 >>= 1
                idx2 -= 1
        return result
    

N, Q = map(int, input().split())
query = [tuple(map(int, input().split())) for i in range(Q)]
row = LazyPropSegmentTree([N]*(N+1))
column = LazyPropSegmentTree([N]*(N+1))

ans = (N-2) ** 2
for t, x in query:
    if t == 1:
        n = row.query(x, x+1)
        ans -= n - 2
        column.update(2, n+1, x)
    else:
        n = column.query(x, x+1)
        ans -= n - 2
        row.update(2, n+1, x)

print(ans)

Submission status: Wrong Answer

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
# mod = 998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 1<<32-1
# INF = 10**18

class SegTree:
    """
    init(init_val, ide_ele): 配列init_valで初期化 O(N)
    update(k, x): k番目の値をxに更新 O(logN)
    query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
    """
    def __init__(self, init_val, segfunc, ide_ele):
        """
        init_val: 配列の初期値
        segfunc: 区間にしたい操作
        ide_ele: 単位元
        n: 要素数
        num: n以上の最小の2のべき乗
        tree: セグメント木(1-index)
        """
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        # 配列の値を葉にセット
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        # 構築していく
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        """
        k番目の値をxに更新
        k: index(0-index)
        x: update value
        """
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        """
        [l, r)のsegfuncしたものを得る
        l: index(0-index)
        r: index(0-index)
        """
        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

def main():
    n,q = map(int,ipt().split())
    sm = (n-2)**2
    sg1 = SegTree([1]*n,max,1)
    sg2 = SegTree([1]*n,max,1)
    sg1.update(0,n-1)
    sg2.update(0,n-1)
    for _ in range(q):
        nm,x = map(int,ipt().split())
        if nm == 1:
            mnm = sg1.query(0,x)
            sm -= mnm-1
            pnm = sg2.tree[sg2.num]
            if pnm > x-1:
                sg2.update(0,x-1)
                sg2.update(mnm,pnm)
        else:
            mnm = sg2.query(0,x+1)
            sm -= mnm-1
            pnm = sg1.tree[sg1.num]
            if pnm > x-1:
                sg1.update(0,x-1)
                sg1.update(mnm,pnm)
#        print(sg1.tree[sg1.num::],sg2.tree[sg2.num::])

    print(sm)

    return None

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
# mod = 998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 1<<32-1
# INF = 10**18

class SegTree:
    """
    init(init_val, ide_ele): 配列init_valで初期化 O(N)
    update(k, x): k番目の値をxに更新 O(logN)
    query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
    """
    def __init__(self, init_val, segfunc, ide_ele):
        """
        init_val: 配列の初期値
        segfunc: 区間にしたい操作
        ide_ele: 単位元
        n: 要素数
        num: n以上の最小の2のべき乗
        tree: セグメント木(1-index)
        """
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        # 配列の値を葉にセット
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        # 構築していく
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        """
        k番目の値をxに更新
        k: index(0-index)
        x: update value
        """
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        """
        [l, r)のsegfuncしたものを得る
        l: index(0-index)
        r: index(0-index)
        """
        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

def main():
    n,q = map(int,ipt().split())
    sm = (n-2)**2
    sg1 = SegTree([1]*(n+1),max,1)
    sg2 = SegTree([1]*(n+1),max,1)
    sg1.update(0,n-1)
    sg2.update(0,n-1)
    for _ in range(q):
        nm,x = map(int,ipt().split())
        if nm == 1:
            mnm = sg1.query(0,x)
            sm -= mnm-1
            pnm = sg2.tree[sg2.num]
            if pnm > x-1:
                sg2.update(0,x-1)
                sg2.update(mnm,pnm)
        else:
            mnm = sg2.query(0,x)
            sm -= mnm-1
            pnm = sg1.tree[sg1.num]
            if pnm > x-1:
                sg1.update(0,x-1)
                sg1.update(mnm,pnm)

    print(sm)

    return None

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
# mod = 998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 1<<32-1
# INF = 10**18

class SegTree:
    """
    init(init_val, ide_ele): 配列init_valで初期化 O(N)
    update(k, x): k番目の値をxに更新 O(logN)
    query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
    """
    def __init__(self, init_val, segfunc, ide_ele):
        """
        init_val: 配列の初期値
        segfunc: 区間にしたい操作
        ide_ele: 単位元
        n: 要素数
        num: n以上の最小の2のべき乗
        tree: セグメント木(1-index)
        """
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        # 配列の値を葉にセット
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        # 構築していく
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        """
        k番目の値をxに更新
        k: index(0-index)
        x: update value
        """
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        """
        [l, r)のsegfuncしたものを得る
        l: index(0-index)
        r: index(0-index)
        """
        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

def main():
    n,q = map(int,ipt().split())
    sm = (n-2)**2
    sg1 = SegTree([1]*(n+1),max,1)
    sg2 = SegTree([1]*(n+1),max,1)
    sg1.update(0,n-1)
    sg2.update(0,n-1)
    for _ in range(q):
        nm,x = map(int,ipt().split())
        if nm == 1:
            mnm = sg1.query(0,x)
            sm -= mnm-1
            pnm = sg2.query(0,1)
            if pnm > x-1:
                sg2.update(0,x-1)
                sg2.update(mnm,pnm)
        else:
            mnm = sg2.query(0,x)
            sm -= mnm-1
            pnm = sg1.query(0,1)
            if pnm > x-1:
                sg1.update(0,x-1)
                sg1.update(mnm,pnm)

    print(sm)

    return None

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
# mod = 998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 1<<32-1
# INF = 10**18

class SegTree:
    """
    init(init_val, ide_ele): 配列init_valで初期化 O(N)
    update(k, x): k番目の値をxに更新 O(logN)
    query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
    """
    def __init__(self, init_val, segfunc, ide_ele):
        """
        init_val: 配列の初期値
        segfunc: 区間にしたい操作
        ide_ele: 単位元
        n: 要素数
        num: n以上の最小の2のべき乗
        tree: セグメント木(1-index)
        """
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        # 配列の値を葉にセット
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        # 構築していく
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        """
        k番目の値をxに更新
        k: index(0-index)
        x: update value
        """
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        """
        [l, r)のsegfuncしたものを得る
        l: index(0-index)
        r: index(0-index)
        """
        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

def main():
    n,q = map(int,ipt().split())
    sm = (n-2)**2
    sg1 = SegTree([-1]*(n+1),max,-1)
    sg2 = SegTree([-1]*(n+1),max,-1)
    sg1.update(0,n-1)
    sg2.update(0,n-1)
    for _ in range(q):
        nm,x = map(int,ipt().split())
        if nm == 1:
            mnm = sg1.query(0,x)
            sm -= mnm-1
            pnm = sg2.query(0,1)
            if pnm > x-1:
                sg2.update(0,x-1)
                sg2.update(mnm,pnm)
        else:
            mnm = sg2.query(0,x)
            sm -= mnm-1
            pnm = sg1.query(0,1)
            if pnm > x-1:
                sg1.update(0,x-1)
                sg1.update(mnm,pnm)

    print(sm)

    return None

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
# mod = 998244353
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"
INF = 1<<32-1
# INF = 10**18

class SegTree:
    """
    init(init_val, ide_ele): 配列init_valで初期化 O(N)
    update(k, x): k番目の値をxに更新 O(logN)
    query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
    """
    def __init__(self, init_val, segfunc, ide_ele):
        """
        init_val: 配列の初期値
        segfunc: 区間にしたい操作
        ide_ele: 単位元
        n: 要素数
        num: n以上の最小の2のべき乗
        tree: セグメント木(1-index)
        """
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        # 配列の値を葉にセット
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        # 構築していく
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        """
        k番目の値をxに更新
        k: index(0-index)
        x: update value
        """
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        """
        [l, r)のsegfuncしたものを得る
        l: index(0-index)
        r: index(0-index)
        """
        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

def main():
    n,q = map(int,ipt().split())
    sm = (n-2)**2
    sg1 = SegTree([-1]*(n+1),max,-1)
    sg2 = SegTree([-1]*(n+1),max,-1)
    sg1.update(0,n-1)
    sg2.update(0,n-1)
    for _ in range(q):
        nm,x = map(int,ipt().split())
        if nm == 1:
            mnm = sg1.query(0,x+1)
            sm -= mnm-1
            pnm = sg2.query(0,1)
            if pnm >= x:
                sg2.update(0,x-1)
                sg2.update(mnm,x-1)
                sg2.update(mnm+1,pnm)
        else:
            mnm = sg2.query(0,x+1)
            sm -= mnm-1
            pnm = sg1.query(0,1)
            if pnm >= x:
                sg1.update(0,x-1)
                sg1.update(mnm,x-1)
                sg1.update(mnm+1,pnm)

    print(sm)

    return None

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations,product#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal
from argparse import ArgumentParser

args=ArgumentParser()
args.add_argument('-loc', '--local', type=bool,default=False)
LOCAL=args.parse_args().local

def input(): 
    x=sys.stdin.readline(); 
    if x[-1]=="\n": 
        return x.rstrip() 
    return x
    
def printe(*x):_=print("## ",*x,file=sys.stderr) if LOCAL else 0
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def binr(x): return bin(x)[2:]
def bitcount(x): #xは64bit整数
    x= x - ((x >> 1) & 0x5555555555555555)
    x= (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x= (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f 
    x+= (x >> 8); x+= (x >> 16); x+= (x >> 32) 
    return x & 0x7f

class segtree():#seg=segtree(A),単位元とsegfuncを指定すること
    def __init__(self,A,ide=1000000000):#単位元とsegfuncを指定すること
        n=len(A)
        num=2**(n-1).bit_length()#n以上の最小の2のべき乗
        seg=[ide]*(2*num-1)
        segfunc=self.segfunc
        self.ide,self.n,self.num,self.seg = ide, n, num, seg
        self.A=deepcopy(A)
        for i in range(n): 
            seg[i+num-1]=A[i]#setvalue
        for i in range(num-2,-1,-1):seg[i]=segfunc(seg[2*i+1],seg[2*i+2])#build
    
    def segfunc(self,x,y):return min(x,y) #seg木の基本関数
    
    def get(self,i): return self.A[i]

    def update(self,k,x):#Aのk番目の要素をxに置き換える,計算量log(N)
        k += self.num-1
        seg,segfunc=self.seg,self.segfunc
        seg[k] = x
        while k:
            k = (k-1)//2
            seg[k] = segfunc(seg[k*2+1],seg[k*2+2])
    
    def query(self,p,q):#区間[p,q)の累積segfuncを求める,計算量log(N)
        if q<=p: return self.ide
        num,segfunc,seg=self.num,self.segfunc,self.seg
        p += num-1; q += num-2
        res=self.ide
        while q-p>1:
            if p&1 == 0: res = segfunc(res,seg[p])
            if q&1 == 1:
                res = segfunc(res,seg[q])
                q -= 1
            p,q = p//2, (q-1)//2
        if p == q: res = segfunc(res,seg[p])
        else: res = segfunc(segfunc(res,seg[p]),seg[q])
        return res 
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=True)  #二個目の要素で降順並び替え

    #N = int(input())
    N, Q = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    S = tuple(tuple(map(int, input().split())) for i in range(Q)) #改行行列

    tot=(N-2)*(N-2)
    seg1=segtree([N]*(N+1))
    seg2=segtree([N]*(N+1))
    l1=[N]*(N+1)
    l2=[N]*(N+1)
    for t,x in S:
        if t==1:
            place=seg2.query(x,N+1)
            tot-=place-2
            seg1.update(place,min(seg1.get(place),x))
        else:
            place=seg1.query(x,N+1)
            tot-=place-2
            seg2.update(place,min(seg2.get(place),x))
        #printe(place,l1)
    print(tot)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
class LazyPropSegmentTree:
    def __init__(self, a):
        self.padding = float('inf')        
        self.n = len(a)
        self.N = 1 << (self.n-1).bit_length()
        self.seg_data = [self.padding]*(self.N-1) + a + [self.padding]*(self.N-self.n)
        self.lazy = [None] * (2*self.N - 1)
        for i in range(2*self.N-2, 0, -2):
            self.seg_data[(i-1)>>1] = min(self.seg_data[i], self.seg_data[i-1])
    
    def __len__(self):
        return self.n
    
    def indices_generator(self, i, j):
        # [i, j)
        # [idx1, idx2)を部分的に含むインデックスを降順にyieldするジェネレータ
        idx1 = self.N + i
        idx2 = self.N + j
        lm = (idx1 // (idx1 & -idx1)) >> 1
        rm = (idx2 // (idx2 & -idx2)) >> 1
        while 0 < idx1 < idx2:
            if idx2 <= rm:
                yield idx2-1
            if idx1 <= lm:
                yield idx1-1
            idx1 >>= 1
            idx2 >>= 1
        while idx1:
            yield idx1-1
            idx1 >>= 1
    
    def propagate_down(self, indices):
        # 遅延させていた値を伝搬させる
        # indicesは昇順
        for idx in indices:
            v = self.lazy[idx]
            if v is not None:
                idx1, idx2 = 2*idx + 1, 2*idx + 2
                self.lazy[idx1] = self.lazy[idx2] = v
                self.seg_data[idx1] = self.seg_data[idx2] = v
                self.lazy[idx] = None
    
    def propagate_up(self, indices):
        for idx in indices:
            idx1, idx2 = 2*idx + 1, 2*idx + 2
            self.seg_data[idx] = min(self.seg_data[idx1], self.seg_data[idx2])
    
    def propagate_all(self):
        indices = [i for i in range(self.N-1)]
        self.propagate_down(indices)
        self.propagate_up(indices[::-1])
    
    def update(self, i, j, x):
        # [i, j)の区間の値をxに変更する
        *should_prop, = self.indices_generator(i, j)
        self.propagate_down(should_prop[::-1])
        idx1 = self.N - 1 + i
        idx2 = self.N - 2 + j
        while idx1 < idx2 + 1:
            if idx1&1 == 0: # idx1が偶数
                v = min(self.seg_data[idx1], x)
                self.lazy[idx1] = self.seg_data[idx1] = v
            if idx2&1 == 1: # idx2が奇数
                v = min(self.seg_data[idx2], x)
                self.lazy[idx2] = self.seg_data[idx2] = v
            idx1 >>= 1
            idx2 >>= 1
            idx2 -= 1
        self.propagate_up(should_prop)
    
    def query(self, i, j):
        # [i, j)
        *should_prop, = self.indices_generator(i, j)
        self.propagate_down(should_prop[::-1])
        idx1 = self.N - 1 + i
        idx2 = self.N - 2 + j
        result = self.padding
        while idx1 < idx2 + 1:
                if idx1&1 == 0: # idx1が偶数
                    result = min(result, self.seg_data[idx1])
                if idx2&1 == 1: # idx2が奇数
                    result = min(result, self.seg_data[idx2])                
                idx1 >>= 1
                idx2 >>= 1
                idx2 -= 1
        return result

N, Q = map(int, input().split())
query = [tuple(map(int, input().split())) for i in range(Q)]
row = LazyPropSegmentTree([N]*(N+1))
column = LazyPropSegmentTree([N]*(N+1))


ans = (N-2) ** 2
for t, x in query:
    if t == 1:
        n = row.query(x, x+1)
        # print(n)
        ans -= n - 2
        column.update(2, n+1, x)
    else:
        n = column.query(x, x+1)
        # print(n)
        ans -= n - 2
        row.update(2, n+1, x)

print(ans)

Submission status: Wrong Answer

Solution code:
n, q = map(int, input().split())
l = [0]*n; u = [0]*n; lmin = n-2; umin = n-2; lgoal = n; ugoal = n
for _ in range(q):
    s, t = map(int, input().split())
    if s == 1:
        if t > ugoal+1: u[t-1] = 0
        else:
            for i in range(t, ugoal-1):u[i] = umin
            lmin = t-2; ugoal = t
    else:
        if t > lgoal+1: l[t-1] = 0
        else:
            for i in range(t, lgoal-1):l[i] = lmin
            umin = t-2; lgoal = t
print(sum(l)+sum(u)+lmin*umin)

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.buffer.readline

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


class SegmentTree:
    ele = 10 ** 10
    func = min
    # SEG木は1-index
    # Aに関しては0-index

    def __init__(self, n):  # Aは0-idx
        self.n = n
        self.num = 2 ** ((self.n - 1).bit_length())
        self.SEG = [self.ele] * (2 * self.num)

    def search(self, idx):
        return self.SEG[idx + self.num]

    def initialize(self, A):
        for i in range(self.n):
            self.SEG[i + self.num] = A[i]
        for i in range(self.num - 1, 0, -1):
            self.SEG[i] = self.func(self.SEG[2 * i], self.SEG[2 * i + 1])

    def update(self, idx, val):
        idx += self.num
        self.SEG[idx] = val
        idx //= 2
        while idx:
            self.SEG[idx] = self.func(self.SEG[2 * idx], self.SEG[2 * idx + 1])
            idx //= 2

    def query(self, left, right):
        # maspy式。開区間のママ処理する
        # left, rightで値を分けているのは交換法則不成立のときのため
        # 開区間→Rが奇数→右端が偶数→1ずらしてから計算
        # 　下から上への遷移は2で割る
        # juppy氏は閉区間に直していた
        resleft = self.ele
        resright = self.ele
        left += self.num
        right += self.num
        while right - left > 0:
            if left % 2 == 1:
                resleft = self.func(resleft, self.SEG[left])
                left += 1
            if right % 2 == 1:
                right -= 1
                resright = self.func(resright, self.SEG[right])
            left //= 2
            right //= 2
        return self.func(resleft, resright)


ans = 0

tate = SegmentTree(n)
yoko = SegmentTree(n)

for i in range(q):
    s, x = map(int, input().split())
    x -= 1
    if s == 1:
        temp = tate.query(x, n)
        # print("t", i, temp)
        if temp == 10 ** 10:
            temp = n - 1
        now = yoko.search(temp)
        now = min(now, temp)
        yoko.update(now, x)
        ans += max(0, temp - 1)
    else:
        temp = yoko.query(x, n)
        # print("t", i, temp)
        if temp == 10 ** 10:
            temp = n - 1
        now = tate.search(temp)
        now = min(now, temp)
        tate.update(now, x)
        ans += max(0, temp - 1)
    # print("a", i, temp - 1)
print((n - 2) ** 2 - ans)

Submission status: Wrong Answer

Solution code:
import sys

input = sys.stdin.buffer.readline

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


class SegmentTree:
    ele = 10 ** 10
    func = min
    # SEG木は1-index
    # Aに関しては0-index

    def __init__(self, n):  # Aは0-idx
        self.n = n
        self.num = 2 ** ((self.n - 1).bit_length())
        self.SEG = [self.ele] * (2 * self.num)

    def search(self, idx):
        return self.SEG[idx + self.num]

    def initialize(self, A):
        for i in range(self.n):
            self.SEG[i + self.num] = A[i]
        for i in range(self.num - 1, 0, -1):
            self.SEG[i] = self.func(self.SEG[2 * i], self.SEG[2 * i + 1])

    def update(self, idx, val):
        idx += self.num
        self.SEG[idx] = val
        idx //= 2
        while idx:
            self.SEG[idx] = self.func(self.SEG[2 * idx], self.SEG[2 * idx + 1])
            idx //= 2

    def query(self, left, right):
        # maspy式。開区間のママ処理する
        # left, rightで値を分けているのは交換法則不成立のときのため
        # 開区間→Rが奇数→右端が偶数→1ずらしてから計算
        # 　下から上への遷移は2で割る
        # juppy氏は閉区間に直していた
        resleft = self.ele
        resright = self.ele
        left += self.num
        right += self.num
        while right - left > 0:
            if left % 2 == 1:
                resleft = self.func(resleft, self.SEG[left])
                left += 1
            if right % 2 == 1:
                right -= 1
                resright = self.func(resright, self.SEG[right])
            left //= 2
            right //= 2
        return self.func(resleft, resright)


ans = 0

tate = SegmentTree(n)

yoko = SegmentTree(n)

for i in range(q):
    s, x = map(int, input().split())
    x -= 1
    if s == 1:
        temp = tate.query(x, n)
        # print("t", i, temp)
        if temp == 10 ** 10:
            temp = n - 1
        now = yoko.search(temp)
        now = min(now, temp)
        yoko.update(now, x)
        ans += temp - 1
    else:
        temp = yoko.query(x, n)
        # print("t", i, temp)
        if temp == 10 ** 10:
            temp = n - 1
        now = tate.search(temp)
        now = min(now, temp)
        tate.update(now, x)
        ans += temp - 1
    # print("a", i, temp - 1)
print((n - 2) ** 2 - ans)