結果

問題 No.1194 Replace
コンテスト
ユーザー roaris
提出日時 2020-08-22 17:44:16
言語 PyPy3
(7.3.17)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
AC  
実行時間 698 ms / 2,000 ms
コード長 781 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 254 ms
コンパイル使用メモリ 84,864 KB
実行使用メモリ 291,072 KB
最終ジャッジ日時 2026-05-04 06:14:00
合計ジャッジ時間 12,152 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge1_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import sys
input = sys.stdin.readline
from collections import *

def bfs(s):
    if ma[s]!=-1:
        return
    
    q = deque([s])
    ma[s] = s
    
    while q:
        v = q.popleft()
        
        for nv in G[v]:
            if ma[nv]==-1:
                ma[nv] = s
                q.append(nv)

N, M = map(int, input().split())
BC = [tuple(map(int, input().split())) for _ in range(M)]
l = []

for B, C in BC:
    l.append(B-1)
    l.append(C-1)

l = list(set(l))
l.sort()
idx = defaultdict(int)

for i in range(len(l)):
    idx[l[i]] = i

G = [[] for _ in range(len(l))]

for B, C in BC:
    G[idx[C-1]].append(idx[B-1])

ma = [-1]*len(l)

for i in range(len(l)-1, -1, -1):
    bfs(i)

ans = N*(N+1)//2

for li in l:
    ans -= li
    ans += l[ma[idx[li]]]

print(ans)
0