結果

問題 No.2756 GCD Teleporter
コンテスト
ユーザー n_bitand_n_per_3
提出日時 2026-07-21 11:41:24
言語 PyPy3
(7.3.17)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
AC  
実行時間 301 ms / 2,000 ms
+ 818µs
コード長 2,694 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 424 ms
コンパイル使用メモリ 95,984 KB
実行使用メモリ 273,208 KB
最終ジャッジ日時 2026-07-21 11:41:53
合計ジャッジ時間 10,259 ms
ジャッジサーバーID
(参考情報)
judge3_1 / judge1_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 36
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

# Varified
# https://judge.yosupo.jp/submission/314547
# https://atcoder.jp/contests/abc350/submissions/70012959
# https://atcoder.jp/contests/abc333/submissions/70015327

class UnionFind:
  def __init__(self,N):
    self.parent = [-1]*N
    self.groupcount = N

  def union(self,x,y):
    fx = self.find(x)
    fy = self.find(y)
    if fx != fy: # x,y の属する木が異なる
      self.groupcount -= 1
      if self.parent[fx] <= self.parent[fy]: # xの木のサイズ >= yの木のサイズ
        self.parent[fx] += self.parent[fy]
        self.parent[fy] = fx
      else:
        self.parent[fy] += self.parent[fx]
        self.parent[fx] = fy


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

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

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

  def groups(self):
    A = sorted(set(self.find(i) for i in range(len(self.parent))))
    d = {v:i for i,v in enumerate(A)}
    res = [[] for i in range(len(A))]
    for i in range(len(self.parent)):
      res[d[self.find(i)]].append(i)
    return res

  def groupsizes(self):
    return [len(g) for g in self.groups()]

# ======================================

from collections import defaultdict

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

M = max(A)

mpf = [i for i in range(M+1)]
for i in range(2,M+1):
  if mpf[i] == i:
    for j in range(2*i, M+1,i):
      mpf[j] = i

d = defaultdict(set)

for i,a in enumerate(A):
  while a > 1:
    p = mpf[a]
    a //= p
    d[p].add(i)


UF = UnionFind(N)

for _,arr in d.items():
  l = len(arr)
  r = arr.pop()
  for v in arr:
    UF.union(r, v)

if UF.groupcount == 1:
  ans = 0
elif 2 in d:
  ans = 2 * (UF.groupcount - 1)
elif 3 in d:
  ans = min(2*UF.groupcount, 3*(UF.groupcount-1))
else:
  ans = 2 * UF.groupcount

print(ans)


"""
if 連結成分がただ1である:
  -> 何もしなくてよい
else:
  if 2の倍数が所属する連結成分がある:
    if 3の倍数が所属する連結成分がある:
      if 2の倍数と3の倍数が同じ連結成分に属する:
        -> 2の倍数以外を全部2倍する
      else:
        -> 2の倍数以外を全部2倍する
    else:
      -> 2の倍数以外を全部2倍する
  else:
    if 3の倍数が所属する連結成分がある:
      if 3の倍数が所属しない連結成分の個数がただ1つである:
        -> 3の倍数が所属しない連結成分を3倍する
      else:
        -> 全部の連結成分を2倍する
    else:
      -> 全部の連結成分を2倍する
"""





0