結果
問題 | No.1813 Magical Stones |
ユーザー | 👑 SPD_9X2 |
提出日時 | 2022-01-14 22:28:09 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 271 ms / 2,000 ms |
コード長 | 3,217 bytes |
コンパイル時間 | 296 ms |
コンパイル使用メモリ | 81,992 KB |
実行使用メモリ | 137,264 KB |
最終ジャッジ日時 | 2024-11-20 12:02:01 |
合計ジャッジ時間 | 7,433 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 4 |
other | AC * 40 |
ソースコード
""" グラフを強連結にすればよい とりあえず SCCする DAGになる S1,G1 S2,G2 ... S3,G3 さて, StartとGoalがあるやつは 上手くやればくっ付けられる """ import sys from sys import stdin import sys 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 N,M = map(int,stdin.readline().split()) AB = [] g = scc_graph(N) for i in range(M): A,B = map(int,stdin.readline().split()) A -= 1;B -= 1 AB.append( (A,B) ) g.add_edge(A,B) scc = g.scc() dic = {} for i in range(len(scc)): for v in scc[i]: dic[v] = i inlis = [0] * len(scc) olis = [0] * len(scc) if len(scc) == 1: print (0) sys.exit() for A,B in AB: if dic[A] == dic[B]: continue olis[ dic[A] ] += 1 inlis[dic[B]] += 1 inone = 0 onone = 0 for i in inlis: if i == 0: inone += 1 for i in olis: if i == 0: onone += 1 ans = max(inone,onone) print (ans)