結果

問題 No.1917 LCMST
ユーザー tamato
提出日時 2022-04-30 00:26:05
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 2,733 ms / 4,000 ms
コード長 1,955 bytes
コンパイル時間 196 ms
コンパイル使用メモリ 81,920 KB
実行使用メモリ 328,852 KB
最終ジャッジ日時 2024-06-29 06:19:54
合計ジャッジ時間 61,571 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 42
権限があれば一括ダウンロードができます

ソースコード

diff #

mod = 998244353
NN = 10 ** 5


def main():
    import sys
    from collections import Counter
    input = sys.stdin.readline

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

        def find_root(self, x):
            while self.root[x] >= 0:
                x = self.root[x]
            return x

        def unite(self, x, y):
            x = self.find_root(x)
            y = self.find_root(y)
            if x == y:
                return
            elif self.rnk[x] > self.rnk[y]:
                self.root[x] += self.root[y]
                self.root[y] = x
            else:
                self.root[y] += self.root[x]
                self.root[x] = y
                if self.rnk[x] == self.rnk[y]:
                    self.rnk[y] += 1

        def isSameGroup(self, x, y):
            return self.find_root(x) == self.find_root(y)

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

    div = [[] for _ in range(NN + 1)]
    for d in range(1, NN + 1):
        for x in range(1, NN + 1):
            if d * x > NN:
                break
            div[d * x].append(d)

    N = int(input())
    A = list(map(int, input().split()))

    C = Counter(A)
    ans = 0
    A_sorted = sorted(list(set(A)))
    D = [[] for _ in range(NN + 1)]
    for i, a in enumerate(A_sorted):
        ans += a * (C[a] - 1)
        for d in div[a]:
            D[d].append(a)

    if len(A_sorted) == 1:
        print(ans)
        exit()

    UF = UnionFind(NN)
    E = []
    for d in range(1, NN + 1):
        if len(D[d]) > 1:
            a0 = D[d][0]
            for a in D[d][1:]:
                E.append((a * a0 // d, a, a0))
    E.sort(key=lambda x: x[0])
    for x, a, b in E:
        if UF.isSameGroup(a, b):
            continue
        ans += x
        UF.unite(a, b)
    print(ans)


if __name__ == '__main__':
    main()
0