結果

問題 No.1553 Lovely City
ユーザー ansainansain
提出日時 2021-06-18 22:24:14
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 5,548 bytes
コンパイル時間 285 ms
コンパイル使用メモリ 82,560 KB
実行使用メモリ 176,744 KB
最終ジャッジ日時 2024-06-22 20:49:59
合計ジャッジ時間 23,161 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 51 ms
61,568 KB
testcase_01 AC 50 ms
62,080 KB
testcase_02 AC 330 ms
130,796 KB
testcase_03 AC 61 ms
65,792 KB
testcase_04 AC 61 ms
66,004 KB
testcase_05 AC 69 ms
71,168 KB
testcase_06 AC 60 ms
66,688 KB
testcase_07 AC 58 ms
65,664 KB
testcase_08 AC 771 ms
149,656 KB
testcase_09 WA -
testcase_10 AC 829 ms
152,672 KB
testcase_11 WA -
testcase_12 WA -
testcase_13 AC 662 ms
134,168 KB
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 AC 708 ms
136,776 KB
testcase_18 WA -
testcase_19 WA -
testcase_20 WA -
testcase_21 WA -
testcase_22 WA -
testcase_23 WA -
testcase_24 WA -
testcase_25 WA -
testcase_26 WA -
testcase_27 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import defaultdict, Counter, deque
from itertools import permutations, combinations, product, combinations_with_replacement, groupby, accumulate
import operator
from math import sqrt, gcd, factorial
from copy import deepcopy
# from math import isqrt, prod,comb  # python3.8用(notpypy)
#from bisect import bisect_left,bisect_right
#from functools import lru_cache,reduce
#from heapq import heappush,heappop,heapify,heappushpop,heapreplace
#from networkx.utils import UnionFind
#from numba import njit, b1, i1, i4, i8, f8
#from scipy.sparse import csr_matrix
#from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, NegativeCycleError
# numba例 @njit(i1(i4[:], i8[:, :]),cache=True) 引数i4配列、i8 2次元配列,戻り値i1
def input(): return sys.stdin.readline().rstrip()
def divceil(n, k): return 1+(n-1)//k  # n/kの切り上げを返す
def yn(hantei, yes='Yes', no='No'): print(yes if hantei else no)

class scc_graph:
 
    def __init__(self, N):
        self.N = N
        self.edges = []
 
    def csr(self):
        self.start = [0]*(self.N+1)
        self.elist = [0]*len(self.edges)
        for e in self.edges:
            self.start[e[0]+1] += 1
        for i in range(1, self.N+1):
            self.start[i] += self.start[i-1]
        counter = self.start[:]
        for e in self.edges:
            self.elist[counter[e[0]]] = e[1]
            counter[e[0]] += 1
 
    def add_edge(self, v, w):
        self.edges.append((v, w))
 
    def scc_ids(self):
        self.csr()
        N = self.N
        now_ord = group_num = 0
        visited = []
        low = [0]*N
        order = [-1]*N
        ids = [0]*N
        parent = [-1]*N
        stack = []
        for i in range(N):
            if order[i] == -1:
                stack.append(i)
                stack.append(i)
                while stack:
                    v = stack.pop()
                    if order[v] == -1:
                        low[v] = order[v] = now_ord
                        now_ord += 1
                        visited.append(v)
                        for i in range(self.start[v], self.start[v+1]):
                            to = self.elist[i]
                            if order[to] == -1:
                                stack.append(to)
                                stack.append(to)
                                parent[to] = v
                            else:
                                low[v] = min(low[v], order[to])
                    else:
                        if low[v] == order[v]:
                            while True:
                                u = visited.pop()
                                order[u] = N
                                ids[u] = group_num
                                if u == v:
                                    break
                            group_num += 1
                        if parent[v] != -1:
                            low[parent[v]] = min(low[parent[v]], low[v])
        for i, x in enumerate(ids):
            ids[i] = group_num-1-x
 
        return group_num, ids
 
    def scc(self):
        group_num, ids = self.scc_ids()
        groups = [[] for _ in range(group_num)]
        for i, x in enumerate(ids):
            groups[x].append(i)
        return groups

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.group_num = 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

        self.group_num -= 1
        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 self.group_num

    def all_group_members(self):
        self.all_group_member = defaultdict(list)
        for i in range(self.n):
            self.all_group_member[self.find(i)].append(i)
        return self.all_group_member

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def main():
    n,m=map(int, input().split())
    uf=UnionFind(n)
    edges=[[] for i in range(n)]
    for i in range(m):
        a,b=map(lambda x: int(x)-1, input().split())
        uf.union(a,b)
        edges[a].append(b)
    ans=[]
    for mem in uf.all_group_members().values():
        sc=scc_graph(len(mem))
        memdic={mm:i for i,mm in enumerate(mem)}
        memdic2={i:mm for i,mm in enumerate(mem)} 
        for mm in mem:
            for v in edges[mm]:
                sc.add_edge(memdic[mm],memdic[v])
        group=sc.scc()
        for i in range(len(group)-1):
            ans.append([memdic2[group[i][0]]+1,memdic2[group[i+1][0]]+1])
        for gg in group:
            if len(gg)>1:
                for i in range(len(gg)):
                    ans.append([memdic2[gg[i]]+1,memdic2[gg[i-1]]+1])
    print(len(ans))
    for aa in ans:
        print(*aa)

if __name__ == '__main__':
    main()


0