Submission #8424245


Source Code Expand

import sys
input = sys.stdin.readline


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):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


def main():
    N, M = map(int, input().split())
    P = list(map(int, input().split()))
    uf = UnionFind(N+1)
    for i in range(M):
        x, y = map(int, input().split())
        uf.union(x, y)
    ans = 0
    for r in uf.roots():
        ms = uf.members(r)
        p = set()
        for m in ms:
            p.add(P[m-1])
#        print(p, ms)
        ans += len(p & set(ms))
    print(ans)


if __name__ == '__main__':
    main()

Submission Info

Submission Time
Task D - Equals
User takeuchi839
Language PyPy3 (2.4.0)
Score 0
Code Size 1692 Byte
Status TLE
Exec Time 2108 ms
Memory 98264 KB

Judge Result

Set Name Sample All
Score / Max Score 0 / 0 0 / 400
Status
AC × 4
AC × 18
TLE × 5
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 179 ms 38256 KB
0_001.txt AC 184 ms 38256 KB
0_002.txt AC 181 ms 38256 KB
0_003.txt AC 180 ms 38256 KB
1_004.txt AC 295 ms 41816 KB
1_005.txt TLE 2107 ms 57304 KB
1_006.txt AC 630 ms 98264 KB
1_007.txt AC 177 ms 38256 KB
1_008.txt AC 184 ms 38256 KB
1_009.txt AC 178 ms 38256 KB
1_010.txt AC 186 ms 38256 KB
1_011.txt AC 184 ms 38512 KB
1_012.txt AC 184 ms 39024 KB
1_013.txt AC 190 ms 38640 KB
1_014.txt AC 202 ms 40048 KB
1_015.txt AC 200 ms 39280 KB
1_016.txt AC 204 ms 39664 KB
1_017.txt AC 202 ms 40048 KB
1_018.txt AC 293 ms 43096 KB
1_019.txt TLE 2107 ms 56408 KB
1_020.txt TLE 2107 ms 56408 KB
1_021.txt TLE 2107 ms 56920 KB
1_022.txt TLE 2108 ms 73176 KB