結果

問題 No.1194 Replace
ユーザー mkawa2mkawa2
提出日時 2021-09-20 22:11:42
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,139 ms / 2,000 ms
コード長 2,288 bytes
コンパイル時間 211 ms
コンパイル使用メモリ 82,456 KB
実行使用メモリ 319,408 KB
最終ジャッジ日時 2024-07-02 23:00:35
合計ジャッジ時間 21,329 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

# sys.setrecursionlimit(200005)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
def SI(): return sys.stdin.readline().rstrip()
dij = [(0, 1), (-1, 0), (0, -1), (1, 0)]
# dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
inf = 10**16
# md = 998244353
md = 10**9+7

# 各強連結成分をリストにしてトポロジカル順に返す
def SCC(to, ot, ver):
    # トポロジカルソート
    fin = defaultdict(lambda: -1)
    topo = []
    for u in ver:
        if fin[u] != -1: continue
        stack = [u]
        while stack:
            u = stack[-1]
            if fin[u] == -1:
                fin[u] = 0
                for v in to[u]:
                    if fin[v] != -1: continue
                    stack.append(v)
            else:
                stack.pop()
                if fin[u] == 0:
                    fin[u] = 1
                    topo.append(u)
    # 逆辺でdfs
    res = []
    while topo:
        u = topo.pop()
        if fin[u] != 1: continue
        fin[u] = 2
        cur = [u]
        i = 0
        while i < len(cur):
            u = cur[i]
            for v in ot[u]:
                if fin[v] == 2: continue
                fin[v] = 2
                cur.append(v)
            i += 1
        res.append(cur)

    return res

from collections import defaultdict

n, m = LI()
to = defaultdict(list)
ot = defaultdict(list)
ver = set()
for _ in range(m):
    b, c = LI()
    to[b].append(c)
    ot[c].append(b)
    ver.add(b)
    ver.add(c)
# print(to)
# print(ot)

gg = SCC(to, ot, ver)
gn = len(gg)
# print(gg)

val = []
utog = defaultdict(int)
for g, uu in enumerate(gg):
    val.append(max(uu))
    for u in uu: utog[u] = g

for g in range(gn)[::-1]:
    uu = gg[g]
    for u in uu:
        for v in ot[u]:
            h = utog[v]
            if g == h: continue
            val[h] = max(val[h], val[g])

ans = n*(n+1)//2
for g, uu in enumerate(gg):
    ans += val[g]*len(uu)-sum(uu)

print(ans)
0