Problem:


Score : 100 points

Problem Statement

You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.

0 u v: Add an edge (u, v).

1 u v: Print 1 if u and v are in the same connected component, 0 otherwise.

Constraints

1 \leq N \leq 200,000

1 \leq Q \leq 200,000

0 \leq u_i, v_i \lt N

Input

Input is given from Standard Input in the following format:

N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q

出力

For each query of the latter type, print the answer.

Sample Input 1

4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3

Sample Output 1

0
1
0
1



Sample input:
4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3


Sample output:
0
1
0
1

Submission status: Runtime Error

Solution code:
# import cProfile

# https://atcoder.jp/contests/practice2/submissions/16598132
# 上記のリンクの提出をいじらせてもらってます。

# from collections import deque


class mf_graph:

    # __slots__ = ["N", "graph", "capacities", "level", "it"]

    def __init__(self, N):
        self.N = N
        self.graph = [[] for _ in range(N)]
        self.capacities = [dict() for _ in range(N)]

    def add_edge(self, v, w, cap):
        self.graph[v].append(w)
        self.graph[w].append(v)
        self.capacities[v][w] = cap
        self.capacities[w][v] = 0

    # def bfs(self, s, t):
    #     self.level = [-1] * self.N
    #     q = deque([s])
    #     self.level[s] = 0
    #     while q:
    #         v = q.popleft()
    #         if v == t:
    #             return True
    #         for w, cap in self.capacities[v].items():
    #             if cap and self.level[w] == -1:
    #                 self.level[w] = self.level[v] + 1
    #                 q.append(w)
    #     return False

    def bfs(self, s, t):
        self.level = [-1] * self.N
        q = [s]
        nq = []
        self.level[s] = 0
        while q:
            nq.clear()
            for v in q:
                if v == t:
                    return True
                for w, cap in self.capacities[v].items():
                    if cap and self.level[w] == -1:
                        self.level[w] = self.level[v] + 1
                        nq.append(w)
            q = nq
        return False

    def dfs(self, s, t, up):
        st = [t]
        while st:
            v = st[-1]
            if v == s:
                flow = up
                for i in range(len(st) - 2):
                    flow = min(flow, self.capacities[st[i+1]][st[i]])
                for i in range(len(st) - 1):
                    self.capacities[st[i]][st[i+1]] += flow
                    self.capacities[st[i+1]][st[i]] -= flow
                return flow
            while self.it[v] < len(self.graph[v]):
                w = self.graph[v][self.it[v]]
                cap = self.capacities[w][v]
                if cap and self.level[w] != -1:
                    if self.level[v] > self.level[w]:
                        st.append(w)
                        break
                self.it[v] += 1
            else:
                st.pop()
                self.level[v] = self.N
        return 0

    def flow(self, s, t, flow_limit=float('inf')):
        flow = 0
        while flow < flow_limit and self.bfs(s, t):
            self.it = [0]*self.N
            while flow < flow_limit:
                f = self.dfs(s, t, flow_limit - flow)
                if not f:
                    break
                flow += f
        return flow

    def min_cut(self, s):
        visited = [False]*self.N
        q = deque([s])
        while q:
            v = q.pop()
            visited[v] = True
            for w, cap in self.capacities[v].items():
                if cap and not visited[w]:
                    q.append(w)

#"""
N, M = map(int, input().split())
S = [list(input()) for i in range(N)]
"""
with open("flow.txt") as f:
    N, M = map(int, f.readline().rstrip().split())
    S = [list(f.readline().rstrip()) for i in range(N)]
#"""
dc = mf_graph(N*M+2)

s = N*M
t = N*M+1
for i in range(N):
    for j in range(M):
        if (i+j) % 2 == 0:
            dc.add_edge(s, M*i+j, 1)
        else:
            dc.add_edge(M*i+j, t, 1)

for i in range(N):
    for j in range(M):
        if j+1 < M and S[i][j] == "." and S[i][j+1] == ".":
            u, v = M*i+j, M*i+j+1
            if (i+j) % 2 == 1:
                u, v = v, u
            dc.add_edge(u, v, 1)
        if i+1 < N and S[i][j] == "." and S[i + 1][j] == ".":
            u, v = M*i+j, M*(i+1)+j
            if (i+j) % 2 == 1:
                u, v = v, u
            dc.add_edge(u, v, 1)

print(dc.flow(s, t))
for u in range(N*M+2):
    ui, uj = divmod(u, M)
    if (ui+uj) % 2 == 1:
        continue
    for v, cap in dc.capacities[u].items():
        if cap != 0:
            continue
        vi, vj = divmod(v, M)
        if u != s and u != t and v != s and v != t:
            if ui+1 == vi:
                S[ui][uj] = "v"
                S[vi][vj] = "^"
            elif ui == vi+1:
                S[ui][uj] = "^"
                S[vi][vj] = "v"
            elif uj+1 == vj:
                S[ui][uj] = ">"
                S[vi][vj] = "<"
            elif uj == vj+1:
                S[ui][uj] = "<"
                S[vi][vj] = ">"

for res in S:
    print("".join(res))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
def find(A,x):
    p = A[x]
    if p == x:
        return x
    a = find(A,p)
    A[x] = a
    return a
 
def union(A, x, y):
#    bx, by = sorted([find(A,x), find(A,y)]) # bx, by = find(A,x), find(A,y)だと無限ループ。
    if find(A,x) > find(A,y):
        bx, by = find(A,y), find(A,x)
    else:
        bx, by = find(A,x), find(A,y)
    A[y] = bx
    A[by] = bx

def main():
    N, Q = map( int, input().split())
    TUV = [ tuple( map( int, input().split())) for _ in range(Q)]
    G = [ i for i in range(N)]
    ANS = []
    for t, u, v in TUV:
        if t == 0:
            union(T,u,v)
        else:
            if find(T,u) == find(T,v):
                ANS.append(1)
            else:
                ANS.append(0)
    print("\n".join( map( str, ANS)))
        
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def input():
    return sys.stdin.readline()[:-1]
sys.setrecursionlimit(300000)
class uf:
    def __init__(self,n):
        self.n=n
        self.l=[-1]*n
    def ro(self,n):         #root
        if self.l[n]<0:
            return n
        r=self.ro(self.l[n])
        self.l[n]=r
        return r
    def me(self,a,b):       #merge
        ra=self.ro(a)
        rb=self.ro(b)
        if self.l[ra]>self.l[rb]:
            ra,rb=rb,ra
        if ra!=rb:
            self.l[ra]+=self.l[rb]
            self.l[rb]=ra
    def size(self,n):
        return -self.l[self.ro(n)]
    def sa(self,a,b):       #same
        return self.ro(a)==self.ro(b)
    def rl(self):           #roots list
        return [i for i,v in enumerate(self.l) if v<0]
    
    def len(self):          #len(roots)
        return len(self.rl())
    def ul(self):
        d={n:i for i,n in enumerate(self.rl())}
        m=[[]for i in range(self.len())]
        for i in range(self.n):
            m[d[self.ro(i)]].append(i)
        return m
    def __str__(self):
        return f"{self.ul()}"
    def __setitem__(self,i,v):
        self.l[i]=v
N,Q=map(int,input().split())
g=uf(N)
for i in range(Q):
    t,u,v=map(int,input().split())
    if t:
        if g.sa(u,v):
            print(1)
        else:
            print(0)
    else:
        g.me(u,v)

Submission status: Runtime Error

Solution code:
code = r"""
# distutils: language=c++
# distutils: include_dirs=opt/atcoder-stl
from libcpp cimport bool
from libcpp.vector cimport vector
cdef extern from "<atcoder/dsu>" namespace "atcoder" nogil:
    cdef cppclass dsu:
        dsu(int n)
        int merge(int a, int b)
        bool same(int a, int b)
        int leader(int a)
        int size(int a)
        vector[vector[int]] groups()
from cython.parallel cimport prange
from libc.stdio cimport getchar, putchar
cdef inline int read() nogil:
    cdef int b, c = 0
    while 1:
        b = getchar() - 48
        if b < 0: break
        c = c * 10 + b
    return c
cdef int i
cdef dsu *d = new dsu(read())
for i in prange(read(), nogil=1):
    if read():
        if d.same(read(), read()): putchar(49)
        else: putchar(48)
        putchar(10)
    else: d.merge(read(), read())
"""
import os, sys
if sys.argv[-1] == 'ONLINE_JUDGE':
    open('solve.pyx', 'w').write(code)
    os.system('cythonize -i -3 -b solve.pyx')
import solve

Submission status: Runtime Error

Solution code:
class UnionFind:
    def __init__(self, length):
        self.parent_indexes = [-1]* length
        
    def union(self, i, j):
        if self.are_in_the_same_group(i, j):
            return
        # iが所属する集団のサイズ>=jが所属する集団のサイズにする
        if self.get_group_size(i) < self.get_group_size(j):
            i, j = j, i
                parent_of_i = self.find(i)
        self.parent_indexes[self.find(i)] = - self.get_group_size(i) - self.get_group_size(j)
        self.parent_indexes[self.find(j)] = self.find(i)
        
    # i番目の要素が所属する集団の親nodeのindexを返す
    # メモ化もする
    def find(self, i):
        if self.parent_indexes[i] < 0:
            return i
        parent_index = self.find(self.parent_indexes[i])
        self.parent_indexes[i] = parent_index
        return parent_index

    def get_group_size(self, i):
        return - self.parent_indexes[self.find(i)]
    
    def are_in_the_same_group(self, i, j):
        return self.find(i) == self.find(j)
    
    
n, q = list(map(lambda x: int(x), input().split()))
uf = UnionFind(n)
for _ in range(q):
    t, u, v = list(map(lambda x: int(x), input().split()))
#     print(uf.parent_indexes)
    if t == 0:
        uf.union(u, v)
        continue
    print('1') if uf.are_in_the_same_group(u, v) else print('0')

Submission status: Runtime Error

Solution code:

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

      
n, q = list(map(lambda x: int(x), input().split()))
uf = UnionFind(n)
for _ in range(q):
    t, u, v = list(map(lambda x: int(x), input().split()))
#     print(uf.parent_indexes)
    if t == 0:
        uf.union(u, v)
        continue
    print('1') if uf.are_in_the_same_group(u, v) else print('0')

Submission status: Runtime Error

Solution code:
class UnionFind:
    def __init__(self, length):
        self.parent_indexes = [-1]* length
        
    def union(self, i, j):
        if i == j:
            return
        # iが所属する集団のサイズ>=jが所属する集団のサイズにする
        if self.get_group_size(i) < self.get_group_size(j):
            i, j = j, i
        self.parent_indexes[i] = - self.get_group_size(i) - self.get_group_size(j)
        self.parent_indexes[j] = i
        
    # i番目の要素が所属する集団の親nodeのindexを返す
    # メモ化もする
    def find(self, i):
        if self.parent_indexes[i] < 0:
            return i
#         parent_index = self.find(i)
#         parent_index = self.find(self.parent_indexes[i])
        parent_index = self.find(self.parent_indexes[i])
        self.parent_indexes[i] = parent_index
        return parent_index

    def get_group_size(self, i):
        return - self.parent_indexes[self.find(i)]
    
    def are_in_the_same_group(self, i, j):
        return self.find(i) == self.find(j)
    
    
n, q = list(map(lambda x: int(x), input().split()))
uf = UnionFind(n)
for _ in range(q):
    t, u, v = list(map(lambda x: int(x), input().split()))
    print(uf.parent_indexes)
    if t == 0:
        uf.union(u, v)
        continue
    print('1') if uf.are_in_the_same_group(u, v) else print('0')

Submission status: Runtime Error

Solution code:
class UnionFind:
    def __init__(self, length):
        self.parent_indexes = [-1]* length
        
    def union(self, i, j):
        # iが所属する集団のサイズ>=jが所属する集団のサイズにする
        if self.get_group_size(i) < self.get_group_size(j):
            i, j = j, i
        self.parent_indexes[i] = - self.get_group_size(i) - self.get_group_size(j)
        self.parent_indexes[j] = i
        
    # i番目の要素が所属する集団の親nodeのindexを返す
    # メモ化もする
    def find(self, i):
        if self.parent_indexes[i] < 0:
            return i
#         parent_index = self.find(i)
#         parent_index = self.find(self.parent_indexes[i])
        parent_index = self.find(self.parent_indexes[i])
        self.parent_indexes[i] = parent_index
        return parent_index

    def get_group_size(self, i):
        return - self.parent_indexes[self.find(i)]
    
    def are_in_the_same_group(self, i, j):
        return self.find(i) == self.find(j)
    
    
n, q = list(map(lambda x: int(x), input().split()))
uf = UnionFind(n)
for _ in range(q):
    t, u, v = list(map(lambda x: int(x), input().split()))
    if t == 0:
        uf.union(u, v)
        continue
    print('1') if uf.are_in_the_same_group(u, v) else print('0')

Submission status: Runtime Error

Solution code:
from collections import defaultdict

links = defaultdict(set)
n, q = list(map(lambda x: int(x), input().split()))
for _ in range(n):
    t, u, v = list(map(lambda x: int(x), input().split()))
    if t == 0:
        links[min(u, v)].add(max(u, v))
        links[v].add(u)
        continue
    print('1') if max(u, v) in links[min(u, v)] else print('0')

Submission status: Runtime Error

Solution code:
n,m,t = map(int,input().split())
shop = []
for i in range(n):
    shop.append([0]*t)
cash = []
for i in range(m):
    ts, id1 = map(int,input().split())
    shop[id1-1][ts-1] += 1

for i in range(len(shop)):
    chek = 0
    for j in range(t):
        if shop[i][j] == 0:
            if chek != 0:
                chek-=1
        else:
            chek = chek + shop[i][j]*2
    if chek >= 5:
        cash.append(i)
print(len(cash))

Submission status: Runtime Error

Solution code:
code = r"""
# distutils: language=c++
# distutils: include_dirs=[/home/contestant/.local/lib/python3.8/site-packages/numpy/core/include,/opt/atcoder-stl]
# cython: boundscheck=False
# cython: wraparound=False
from libcpp cimport bool
from libcpp.vector cimport vector
cdef extern from "/opt/atcoder-stl/atcoder/dsu.hpp" namespace "atcoder":
    cpdef cppclass dsu:
        dsu(int n)
        int merge(int a, int b)
        bool same(int a, int b)
        int leader(int a)
        int size(int a)
        vector[vector[int]] groups()
cdef class dsu_:
    cdef dsu *ptr
    def __cinit__(self, int n): self.ptr = new dsu(n)
    def __dealloc__(self): del self.ptr
    cpdef int merge(self,a,b): return self.ptr.merge(a,b)
    cpdef bool same(self,a,b): return self.ptr.same(a,b)
    cpdef int leader(self,a): return self.ptr.leader(a)
    cpdef int size(self,a): return self.ptr.size(a)
    cpdef vector[vector[int]] groups(self): return self.ptr.groups()

cdef extern from "/opt/atcoder-stl/atcoder/fenwicktree.hpp" namespace "atcoder":
    cdef cppclass fenwick_tree[T]:
        fenwick_tree(int n)
        void add(int p, T x)
        T sum(int l, int r)
cdef class fenwick_tree_:
    cdef fenwick_tree[long] *ptr
    def __cinit__(self, int n): self.ptr = new fenwick_tree[long](n)  
    def __dealloc__(self): del self.ptr
    cpdef void add(self, int p, long x): self.ptr.add(p, x)
    cpdef long sum(self, int l, int r): return self.ptr.sum(l, r)
"""
import os
try:
    from atcoder import *
except:
    open('atcoder.pyx', 'w').write(code)
    os.system('cythonize -i -3 -b atcoder.pyx')

N,Q=map(int,input().split())
A=list(map(int,input().split()))
QRS=[list(map(int,input().split())) for i in range(Q)]
f=fenwick_tree_(N)
for i in range(N):
    f.add(i,A[i])
a=[]
for q,r,s in QRS:
    if q==0:
        f.add(r,s)
    else:
        a.append(f.sum(r,s))
print(*a,sep='\n')