結果

問題 No.2289 順列ソート
ユーザー とりゐとりゐ
提出日時 2023-05-05 21:20:52
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 98 ms / 2,000 ms
コード長 1,228 bytes
コンパイル時間 304 ms
コンパイル使用メモリ 86,948 KB
実行使用メモリ 71,832 KB
最終ジャッジ日時 2023-08-15 02:40:35
合計ジャッジ時間 3,635 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 94 ms
71,304 KB
testcase_01 AC 97 ms
71,732 KB
testcase_02 AC 95 ms
71,800 KB
testcase_03 AC 98 ms
71,772 KB
testcase_04 AC 94 ms
71,664 KB
testcase_05 AC 94 ms
71,312 KB
testcase_06 AC 93 ms
71,744 KB
testcase_07 AC 94 ms
71,808 KB
testcase_08 AC 94 ms
71,756 KB
testcase_09 AC 95 ms
71,624 KB
testcase_10 AC 95 ms
71,784 KB
testcase_11 AC 94 ms
71,452 KB
testcase_12 AC 96 ms
71,488 KB
testcase_13 AC 95 ms
71,752 KB
testcase_14 AC 93 ms
71,832 KB
testcase_15 AC 94 ms
71,528 KB
testcase_16 AC 94 ms
71,296 KB
testcase_17 AC 94 ms
71,804 KB
testcase_18 AC 94 ms
71,508 KB
testcase_19 AC 94 ms
71,824 KB
testcase_20 AC 94 ms
71,640 KB
testcase_21 AC 93 ms
71,644 KB
testcase_22 AC 93 ms
71,424 KB
testcase_23 AC 94 ms
71,740 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from sys import stdin
input=lambda :stdin.readline()[:-1]

from collections import defaultdict

class UnionFind():
  def __init__(self,n):
    self.n=n
    self.parents=[-1]*n

  def find(self,x):
    if self.parents[x]<0:
      return x
    else:
      self.parents[x]=self.find(self.parents[x])
      return self.parents[x]

  def union(self,x,y):
    x=self.find(x)
    y=self.find(y)

    if x==y:
      return

    if self.parents[x]>self.parents[y]:
      x,y=y,x

    self.parents[x]+=self.parents[y]
    self.parents[y]=x

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

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

  def members(self,x):
    root=self.find(x)
    return [i for i in range(self.n) if self.find(i)==root]

  def roots(self):
    return [i for i, x in enumerate(self.parents) if x< 0]

  def group_count(self):
    return len(self.roots())

  def all_group_members(self):
    group_members=defaultdict(list)
    for member in range(self.n):
      group_members[self.find(member)].append(member)
    return group_members

n=int(input())
p=list(map(lambda x:int(x)-1,input().split()))
uf=UnionFind(n)
for i in range(n):
  uf.union(i,p[i])
g=uf.all_group_members()
print(n-len(g))
0