結果

問題 No.1687 What the Heck?
ユーザー tktk_snsn
提出日時 2021-09-24 23:13:27
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
WA  
実行時間 -
コード長 1,069 bytes
コンパイル時間 139 ms
コンパイル使用メモリ 12,672 KB
実行使用メモリ 30,240 KB
最終ジャッジ日時 2024-07-05 11:29:02
合計ジャッジ時間 4,134 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 14 WA * 4
権限があれば一括ダウンロードができます

ソースコード

diff #

class UF_tree:
    def __init__(self, n):
        self.root = [-1] * (n + 1)
        self.rank = [0] * (n + 1)

    def find(self, x):
        stack = []
        while self.root[x] >= 0:
            stack.append(x)
            x = self.root[x]
        for i in stack:
            self.root[i] = x
        return x

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

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False
        if x > y:
            x, y = y, x
        self.root[y] += self.root[x]
        self.root[x] = y
        return True

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


N = int(input())
A = list(map(lambda x: int(x) - 1, input().split()))
uf = UF_tree(N + 1)

ans = 0
for i in reversed(range(1, N + 1)):
    p = A[i-1]
    c = uf.find(p + 1)
    if c < N:
        ans += i
        uf.unite(c, c + 1)
    elif uf.find(p) == p:
        uf.unite(p, p + 1)
    else:
        c = uf.find(0)
        ans -= i
        uf.unite(c, c + 1)

print(ans)
0