Submission #8477744


Source Code Expand

#D
N,M = map(int,input().split())
P = list(map(int,input().split()))
XY = [list(map(int,input().split())) for i in range(M)]

#UnionFind
class UF:
    def __init__(self,n):
        self.n = n
        self.root = [-1]*n #root[x]<0 ならxが根かつその値が木の要素数
        self.rank = [0]*n #木の深さ
    def __del__(self):
        pass
        
    def find(self,x):
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]
            
    def unite(self,x,y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        
        if self.rank[x] < self.rank[y]:
            self.root[y] += self.root[x]
            self.root[x] = y
        else:
            self.root[x] += self.root[y]
            self.root[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x]+=1
                
    def same(self,x,y):
        return self.find(x) == self.find(y) #bool
    
    def count(self,x):
        return -self.root[self.find(x)]
    
uf = UF(N)
for xy in XY:
    x,y = xy
    uf.unite(x-1,y-1)
    
ans = 0
for i,p in enumerate(P):
    if uf.same(p-1,i):
        ans+=1
        
print(ans)

Submission Info

Submission Time
Task D - Equals
User OribeYasuna
Language Python (3.4.3)
Score 400
Code Size 1310 Byte
Status AC
Exec Time 735 ms
Memory 34588 KB

Judge Result

Set Name Sample All
Score / Max Score 0 / 0 400 / 400
Status
AC × 4
AC × 23
Set Name Test Cases
Sample 0_000.txt, 0_001.txt, 0_002.txt, 0_003.txt
All 0_000.txt, 0_001.txt, 0_002.txt, 0_003.txt, 1_004.txt, 1_005.txt, 1_006.txt, 1_007.txt, 1_008.txt, 1_009.txt, 1_010.txt, 1_011.txt, 1_012.txt, 1_013.txt, 1_014.txt, 1_015.txt, 1_016.txt, 1_017.txt, 1_018.txt, 1_019.txt, 1_020.txt, 1_021.txt, 1_022.txt
Case Name Status Exec Time Memory
0_000.txt AC 22 ms 3064 KB
0_001.txt AC 18 ms 3192 KB
0_002.txt AC 18 ms 3064 KB
0_003.txt AC 18 ms 3064 KB
1_004.txt AC 468 ms 23688 KB
1_005.txt AC 573 ms 32772 KB
1_006.txt AC 735 ms 34588 KB
1_007.txt AC 18 ms 3064 KB
1_008.txt AC 18 ms 3064 KB
1_009.txt AC 18 ms 3064 KB
1_010.txt AC 18 ms 3064 KB
1_011.txt AC 18 ms 3064 KB
1_012.txt AC 18 ms 3064 KB
1_013.txt AC 22 ms 3188 KB
1_014.txt AC 40 ms 3956 KB
1_015.txt AC 19 ms 3064 KB
1_016.txt AC 19 ms 3064 KB
1_017.txt AC 24 ms 3316 KB
1_018.txt AC 438 ms 23700 KB
1_019.txt AC 105 ms 13812 KB
1_020.txt AC 103 ms 13812 KB
1_021.txt AC 107 ms 13812 KB
1_022.txt AC 697 ms 33860 KB