Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

#!/usr/bin/env python3
import sys

MOD = 1000000007  # type: int


def solve(N: int, A: "List[int]"):
    bA = [[0]*N for _ in range(60)]

    for i in range(N):
        a = format(A[i],'b').zfill(60)
        for k in range(60):
            bA[k][i] = a[k]

    ruiseki = [[()]*N for _ in range(60)]
    for keta in range(60):
        zero = bA[keta].count('0')
        one = bA[keta].count('1')

        for i in range(0,N):
            if bA[keta][i] == '1':
                one -= 1
            else:
                zero -= 1
            ruiseki[keta][i] = (zero,one)
    
    answer = 0
    for keta in range(60):
        a = 0
        for i in range(N):
            if bA[keta][i] == '1':
                ##zeroの個数
                a += ruiseki[keta][i][0]
            else:
                a += ruiseki[keta][i][1]

        answer += a*2**(59-keta)
        answer %= MOD

    print(answer%MOD)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python3
import sys
import numpy as np

MOD = 1000000007  # type: int

def solve(N: int, A: "List[int]"):
    mLEN = len(format(max(A),'b'))

    A = np.array(A)
    ans = 0
    d = 1
    while d < (1 << mLEN):
        cnt = np.count_nonzero(A & d)
        ans += (N - cnt) * cnt * d
        ans %= MOD
        d <<= 1
    print(ans)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()
### BUGGY CODE ###

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
input = sys.stdin.readline


def main():
    n = int(input())
    s = [None] * n
    for i in range(n):
        s[i] = str(input()).replace("\n", "")

    ans = list()
    for i in s:
        count_word = dict()
        for j in i:
            count_word[j] = i.count(j)

        ans.append(count_word)

    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if ans[i] == ans[j]:
                count += 1

    print(count)


if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
input = sys.stdin.readline


def main():
    n = int(input())
    s = [None] * n
    for i in range(n):
        s[i] = str(input()).replace("\n", "")

    ans = dict()
    pairs = 0
    for i in s:
        i = ''.join(sorted(list(i)))

        if i in ans:
            pairs += ans[i]
            ans[i] += 1
            continue

        ans[i] = 1

    print(pairs)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

from functools import lru_cache
import sys
sys.setrecursionlimit(10000)


@lru_cache(maxsize=None)
def rec(i, j, k):
    if i < 0 or j < 0 or k < 0:
        return 0.0
    if i == 0 and j == 0 and k == 0:
        return 0.0
    global N
    return (rec(i-1, j, k)*i + rec(i+1, j-1, k) * j +
            rec(i, j+1, k-1) * k + N) / (i + j + k)


def main():
    global N
    N = int(input())
    a = map(int, input().split())
    single = double = triple = 0
    for sushi in a:
        if sushi == 1:
            single += 1
        elif sushi == 2:
            double += 1
        elif sushi == 3:
            triple += 1
    print(rec(single, double, triple))


if __name__ == "__main__":
    main()


### FIXED CODE ###

def main():
    N = int(input())
    a = map(int, input().split())
    single = double = triple = 0
    for sushi in a:
        if sushi == 1:
            single += 1
        elif sushi == 2:
            double += 1
        elif sushi == 3:
            triple += 1
    dp = [[[0 for i in range(1+single+double+triple-j-k)]
           for j in range(double + triple + 1 - k)] for k in range(triple + 1)]
    for k in range(triple+1):
        for j in range(double + triple + 1-k):
            for i in range(1+single+double+triple-j-k):
                if i == 0 and j == 0 and k == 0:
                    continue
                first = second = third = 0
                if i-1 >= 0 and j >= 0 and k >= 0:
                    first = dp[k][j][i-1]
                if i+1 >= 0 and j-1 >= 0 and k >= 0:
                    second = dp[k][j - 1][i+1]
                if i >= 0 and j+1 >= 0 and k-1 >= 0:
                    third = dp[k-1][j + 1][i]
                dp[k][j][i] = (first*i + second * j +
                               third * k + N) / (i + j + k)
    print(dp[triple][double][single])


if __name__ == "__main__":
    main()
### BUGGY CODE ###

from collections import Counter

H, W, M = [int(n) for n in input().split()]
h = []
w = []
table = {}
for m in range(M):
    tmp = [int(n) for n in input().split()]
    h.append(tmp[0])
    w.append(tmp[1])
    if tmp[0] not in table.keys():
        table[tmp[0]] = [tmp[1]]
    else:
        table[tmp[0]].append(tmp[1])

h_counter = Counter(h)
w_counter = Counter(w)

most_common_h_list = []
most_common_w_list = []

most_common_h_count = 0
for k, v in h_counter.most_common():
    if v < most_common_h_count:
        break
    most_common_h_list.append(k)
    most_common_h_count = v

most_common_w_count = 0
for k, v in w_counter.most_common():
    if v < most_common_w_count:
        break
    most_common_w_list.append(k)
    most_common_w_count = v

ans = 0
finished = False
for hh in most_common_h_list:
    if finished:
        break
    for ww in most_common_w_list:
        if ww in table[hh]:
            tt = most_common_h_count + most_common_w_count - 1
            if tt > ans:
                ans = tt
        else:
            tt = most_common_h_count + most_common_w_count
            if tt > ans:
                ans = tt
            finished = True
            break

print(ans)

### FIXED CODE ###

H, W, M = [int(n) for n in input().split()]
H_freq = [0] * H
W_freq = [0] * W

table = []
for m in range(M):
    h, w = [int(n)-1 for n in input().split()]
    H_freq[h] += 1
    W_freq[w] += 1
    table.append((h, w))

max_h = max(H_freq)
max_w = max(W_freq)
most_freqent_h = [i for i, h in enumerate(H_freq) if h == max_h]
most_freqent_w = [i for i, w in enumerate(W_freq) if w == max_w]

count = 0
for (h, w) in table:
    if H_freq[h] == max_h and W_freq[w] == max_w:
        count += 1

if count < len(most_freqent_h) * len(most_freqent_w):
    print(max_h + max_w)
else:
    print(max_h + max_w - 1)
### BUGGY CODE ###

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Created: Jul, 12, 2020 08:04:43 by Nobody
# $Author$
# $Date$
# $URL$
__giturl__ = "$URL$"


from collections import defaultdict
from collections import deque
from collections import OrderedDict
import itertools
from sys import stdin
input = stdin.readline


def main():
  N = int(input())
  G = [[] for _ in range(N+1)]
  for i in range(N-1):
    u, v, w = map(int, input().split())
    G[u].append((v, w))
    G[v].append((u, w))

  color = [-1 for _ in range(N+1)]
  color[1] = 0
  S = [1]
  while len(S):
    now = S[-1]
    for next_, w in G[now]:
      if not color[next_] == -1:
        continue
      S.append(next_)
      # white, odd
      if color[now]:
        color[next_] = 0 if w % 2 else 1
      # black, even
      else:
        color[next_] = 1 if w % 2 else 0
      break
    else:
      S.pop()

  for i in range(1, N+1):
    print(color[i])


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


### FIXED CODE ###

import sys
from collections import defaultdict, deque

def main():
    input = sys.stdin.readline
    N = int(input())
    d = defaultdict(list)
    for _ in range(N-1):
        u, v, w = map(int, input().split())
        d[u-1].append((v-1, w))
        d[v-1].append((u-1, w))

    dist = [0] * N
    q = deque()
    q.append((0, 0))
    visited = set()

    while len(q) > 0:
        q_ = deque()
        while len(q) > 0:
            node1, cost1 = q.popleft()

            dist[node1] = cost1
            visited.add(node1)

            for node2, cost2 in d[node1]:
                if node2 in visited:
                    continue

                q_.append((node2, cost1 + cost2))

        q = q_

    for d in dist:
        print(d % 2)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

s = input()
num = len(s)

dp = [0]*num
temp = [0]*2019
for i in range(num):
    temp[int(s[i:]) % 2019] += 1

ans = temp[0]
for t in temp:
    if t > 1:
        ans += t*(t-1)/2

print(int(ans))

### FIXED CODE ###

S=input()
N=len(S)
M=2019

remainder=[0]*M
val=0
for i in range(N):
  val=(int(S[N-1-i])*pow(10,i,M)+val)%M
  remainder[val]+=1

ans=remainder[0]
for i in range(2019):
  ans+=remainder[i]*(remainder[i]-1)//2
print(ans)
### BUGGY CODE ###

def ABC073D():
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))
    ABC = [list(map(int, input().split())) for i in range(M)]
    root = [[1000000000 for i in range(N)] for j in range(N)]
    for i, j, k in ABC:
        root[i - 1][j - 1] = k
        root[j - 1][i - 1] = k

    import itertools
    def kumiawase(list_name):  # list_name(リスト)のすべての並び替え
        return itertools.permutations(list_name)

    for i in range(N):
        for j in range(N):
            for k in range(N):
                if root[i][j] > root[i][k] + root[k][j]:
                    root[i][j] = root[i][k] + root[k][j]

    for i in range(N):
        for j in range(N):
            for k in range(N):
                if root[N - i - 1][N - j - 1] > root[N - i - 1][N - k - 1] + root[N - k - 1][N - j - 1]:
                    root[N - i - 1][N - j - 1] = root[N - i - 1][N - k - 1] + root[N - k- 1][N - j - 1]

    a = kumiawase(r)
    ans = float("inf")
    for i in a:
        key = 0
        for j in range(len(i) - 1):
            key += root[i[j] - 1][i[j + 1] - 1]
        if ans > key:
            ans = int(key)
    #print(root)
    print(ans)
ABC073D()

### FIXED CODE ###

def ABC073D():
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))
    ABC = [list(map(int, input().split())) for i in range(M)]
    root = [[1000000000 for i in range(N)] for j in range(N)]
    for i, j, k in ABC:
        root[i - 1][j - 1] = k
        root[j - 1][i - 1] = k

    import itertools
    def kumiawase(list_name):  # list_name(リスト)のすべての並び替え
        return itertools.permutations(list_name)


    from scipy.sparse import csgraph
    root = csgraph.floyd_warshall(root)

    a = kumiawase(r)
    ans = float("inf")
    for i in a:
        key = 0
        for j in range(len(i) - 1):
            key += root[i[j] - 1][i[j + 1] - 1]
        if ans > key:
            ans = int(key)
    #print(root)
    print(ans)
ABC073D()
### BUGGY CODE ###

import itertools
N = int(input())
alst = list(map(int,input().split()))

for i in range(N):
    tmp = alst[i]
    alst.remove(alst[i])
    cnt = 0
    for v in itertools.combinations(alst, 2):
        if v[0] == v[1]:
            cnt += 1
    print(cnt)
    alst.insert(i,tmp)


### FIXED CODE ###

from collections import Counter

N = int(input())
al = list(map(int, input().split()))
C = Counter(al)
# print(C)
# print(C.values())
ans = 0
for i in C.values():
    ans += i * (i - 1) / 2

for a in al:
    k = C[a]
    print(int(ans - (k * (k - 1) / 2) + (k - 1) * (k - 2) / 2))
### BUGGY CODE ###

import itertools
import math
import collections


N, M = map(int, input().split())
MOD = 10 ** 9 + 7

def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors


def nPk(n, k):
    return math.factorial(n) // math.factorial(n-k)


def nCk(n, k):
    return math.factorial(n) // (math.factorial(n-k) * math.factorial(k))

def m():
    ans = 1
    f = prime_factors(M)
    counts = collections.Counter(f)
    l = len(f)
    for k,v in counts.items():
        ans *= nCk(v + N-1, N-1)
    return ans % MOD

print(m())

### FIXED CODE ###

import math
import collections

N, M = map(int, input().split())
MOD = 10 ** 9 + 7


def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors


def comb(n,k,p):
    from math import factorial
    if n < 0 or k < 0 or n < k: return 0
    if n == 0 or k == 0: return 1
    a = factorial(n) % p
    b = factorial(k) % p
    c = factorial(n - k) % p
    return (a * power_func(b, p - 2, p) * power_func(c, p - 2, p)) % p


def power_func(a,b,p):
    if b == 0: return 1
    if b % 2 == 0:
        d = power_func(a, b // 2, p)
        return d * d % p
    if b % 2 == 1:
        return (a * power_func(a, b - 1, p)) % p

def m():
    ans = 1
    f = prime_factors(M)
    counts = collections.Counter(f)
    for k,v in counts.items():
        ans *= comb(v + N-1, N-1, MOD)
    return ans % MOD

print(m())
### BUGGY CODE ###

import sys
#ユークリッドの互除法
def gcd(x, y):
    if x % y == 0:
        return y
    else:
        return gcd(y, x % y)
#入力
N = int(input())
A = list(map(int, input().split()))
#カウントしていく
count= [0] * (1000001)
setwise_gcd = A[0]
for i in range(0,N):
    count[A[i]]+= 1
    setwise_gcd = gcd(setwise_gcd, A[i])

#全体のgcdが1でないならnot coprime
if setwise_gcd != 1:
    print("not coprime")
    sys.exit(0)
#A[x] % i == 0 && A[y] % i == 0 となるx, y が存在しないならpairwise coprime
for i in range(2,1000001):
    divided_count = count[i]
    now_number = 2 * i
    while(now_number<1000001):
        divided_count+= count[now_number]
        now_number+= i
    if(divided_count >= 2):
        print("setwise coprime")
        exit(0)
print("pairwise coprime")


### FIXED CODE ###

import numpy as np
#入力
N = int(input())
A = list(map(int, input().split()))
#カウンターテーブルの用意
count=[0]*(1000001)
for a in A:count[a]+= 1

#全体のgcdが1でないならnot coprime
if np.gcd.reduce(A)!=1:
    print("not coprime")
#A[x] % i == 0 && A[y] % i == 0 となるx, y が存在しないならpairwise coprime
elif np.all([sum(count[i::i])<=1 for i in range(2,10**6+1)]):
    print("pairwise coprime")
else:
    print("setwise coprime")
### BUGGY CODE ###

s = input()
K = int(input())

SS = set()
for i in range(len(s)):
    for j in range(i+1, len(s)+1):
        SS.add(s[i:j])
print(sorted(list(SS))[K-1])

### FIXED CODE ###

s = input()
K = int(input())

SS = set()
for i in range(len(s)):
    for j in range(i+1, i+6):
        SS.add(s[i:j])
print(sorted(list(SS))[K-1])
### BUGGY CODE ###


def comp(ext,list0,dev):
    if list0[int((ext[0]+ext[1])/2)]>dev:
        return ext[0],int((ext[0]+ext[1])/2)
    else:
        return int((ext[0]+ext[1])/2),ext[1]


def bis(a,b,list0,dev):
    ls=[a,b]
    while ls[0]+1<ls[1]:
        ls=comp(ls,list0,dev)
    if list0[ls[0]]==dev:
        return ls[0]-1
    elif list0[ls[1]]==dev:
        return ls[1]-1
    else:
        return ls[0]


n=int(input())
l=[int(x) for x in input().split()]
l.sort()
s=0
for a in range(0,n-2):
    for b in range(a+1,n-1):
        if l[a]+l[b]>l[n-1]:
            c=n-1
        elif l[a]+l[b]<l[b+1]:
            c=b
        else:
            c=bis(b+1,n-1,l,l[a]+l[b])
        s=s+c-b
print(s)


### FIXED CODE ###

def bis_right(lis,dev):
    a=0
    b=len(lis)-1
    while a<b:
        c=(a+b)//2
        if lis[c]>dev:
            b=c
        else:
            a=c+1
    if lis[a]<=dev:
        return a
    return a-1



n=int(input())
l=[int(x) for x in input().split()]
l.sort()
s=0
for a in range(n-2):
    for b in range(a+1,n-1):
        c=bis_right(l[b+1:],l[a]+l[b]-1)
        s+=c+1
print(s)
### BUGGY CODE ###

k,s=map(int,input().split())
cnt=0
for i in range(k+1):
    for j in range(k+1):
        for m in range(k+1):
            if i+j+m==s:
                cnt+=1
            else:
                pass
print(cnt)
    

### FIXED CODE ###

k,s=map(int,input().split())
cnt=0
for i in range(k+1):
    for j in range(k+1):
        z=s-i-j
        if z>=0 and z<=k:
            cnt+=1
print(cnt)
### BUGGY CODE ###

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

a,b,c,k = map(int, input().split())
p = 0
for i in range(k):
    if i+1 <= a:
        p += 1
    elif a < i+1 <= a + b:
        p += 0
    else:
        p -= 1

print(p)        

### FIXED CODE ###

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

a,b,c,k = map(int, input().split())

if a + b >= k:
    if a <= k:
        print(a)
    else:
        print(k)
else:
    print(a - (k - (a + b)))
### BUGGY CODE ###

from collections import deque

s = deque(input())
q = int(input())

for _ in range(q):
    x = input().split()
    
    if(x[0]=='1'):
        s.reverse()
    else:
        s.appendleft(x[2]) if(x[1]=='1') else s.append(x[2])

print(''.join(s))


### FIXED CODE ###

from collections import deque

revFlag = False

s = deque(input())
q = int(input())

for i in range(q):
    a,b,c, *_ = input().split() + [None, None]
    
    if(a == '1'):
        revFlag = not revFlag
        
    else:
        b = int(b)
        if(revFlag):
            b = (int(b)%2)+1
        
        if(b == 1):
            s.appendleft(c)
        else:
            s.append(c)
            
    #print(_,*s, sep="")

if(revFlag):
    s.reverse()
    
print(*s, sep='')
### BUGGY CODE ###

n=int(input())
p=list(map(int,input().split()))
ans=n
for i in range(1,n):
    for j in range(i):
        if p[j]<p[i]:
            ans-=1
            break
print(ans)

### FIXED CODE ###

n=int(input())
p=list(map(int,input().split()))
mini=p[0]
ans=0
for i in range(n):
    if p[i]<=mini:
        ans+=1
        mini=min(p[i],mini)
print(ans)
### BUGGY CODE ###

n,a,b=map(int, input().split())

balls= 0
blue = 0

for i in range(10**18):
  if i % 2 == 0:
    if (balls + a) >= n:
      fill = n - balls
      balls = balls + fill
      blue = blue + fill
      break      
    balls = balls + a
    blue = blue + a
  else:
    if (balls + b) >= n:
      fill = n - balls
      balls = balls + fill
      break
    balls = balls + b

print(blue)

### FIXED CODE ###

n,a,b=map(int, input().split())

balls= 0
blue = 0

time = n // (a+b)
tmp = n % (a+b)
if tmp < a:
  blue = time*a + tmp
else:
  blue = (time+1)*a

print(blue)
### BUGGY CODE ###

n = int(input())
ans = 1
for i in range(1,n+1):ans*=i
print((ans)%((10**9) +7))

### FIXED CODE ###

n = int(input())
ans = 1
for i in range(1,n+1):ans=(ans*i)%(10**9 + 7)
print(ans)
### BUGGY CODE ###

import numpy as np
L, R = map(int, input().split())

minimum=2019
for i in range(L, R):
    for j in range(i+1, R+1):
        tmp = (i*j)%2019
        if minimum>tmp:
            minimum = tmp
        if minimum==0:
            continue
    if minimum==0:
        continue
print(minimum)


### FIXED CODE ###

L, R = map(int, input().split())

minimum=2019
z=0
for i in range(L, R+1):
    for j in range(i+1, R+1):
        tmp = (i*j)%2019
        if minimum>tmp:
            minimum = tmp
        if minimum==0:
            z=1
            break
    if z==1:
        break
    
print(minimum)
### BUGGY CODE ###

from collections import deque

N = int(input())
op = [[]]
for i in range(N):
    op.append(deque(list(map(int, input().split()))))

day = 0
ok = 1
count = (N * (N - 1)) // 2
can = 1
while True:
    if not ok:
        day = -1
        print('ok')
        break
    if count == 0:
        break
    if can == 0:
        day = -1
        break
    played = [0] * (N + 1)
    k = 1
    end_day = 0
    can = 0
    while True:
        if len(op[k]) > 0:
            opponent = op[k][0]
            if len(op[opponent]) > 0:
                if op[opponent][0] == k:
                    if played[k] == 0 and played[opponent] == 0:
                        count -= 1
                        can = 1
                        op[k].popleft()
                        op[opponent].popleft()
                    played[k] = 1
                    played[opponent] = 1
                    k = 1
                    while played[k] == 1:
                        k += 1
                        if k >= N:
                            day += 1
                            end_day = 1
                            break
                else:
                    played[k] = 1
                    if played[opponent] == 0:
                        k = opponent
                    else:
                        k = 1
                        while played[k] == 1:
                            k += 1
                            if k >= N:
                                day += 1
                                end_day = 1
                                break
            else:
                ok = 0
                break
        else:
            played[k] = 1
            k = 1
            while played[k] == 1:
                k += 1
                if k >= N:
                    day += 1
                    end_day = 1
                    break
        if end_day == 1:
            break

print(day)


### FIXED CODE ###

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

    N = int(input())
    A = []
    for _ in range(N):
        A.append(list(map(int, input().split())))

    adj = defaultdict(list)
    in_num = defaultdict(int)
    for i in range(N):
        for j in range(N-2):
            x1 = x2 = i+1
            y1 = A[i][j]
            y2 = A[i][j+1]
            if x1 > y1:
                x1, y1 = y1, x1
            if x2 > y2:
                x2, y2 = y2, x2
            adj[x1*(N+1)+y1].append(x2*(N+1)+y2)
            in_num[x2*(N+1)+y2] += 1
    st = []
    ng = (N * (N - 1)) // 2
    for i in range(1, N+1):
        for j in range(i+1, N+1):
            if in_num[i*(N+1)+j] == 0:
                st.append(i*(N+1)+j)
                ng -= 1
    ans = 0
    while st:
        ans += 1
        st_new = []
        for par in st:
            for child in adj[par]:
                if in_num[child] == 1:
                    st_new.append(child)
                    ng -= 1
                in_num[child] -= 1
        if st_new:
            st = st_new
        else:
            break

    if ng:
        print(-1)
    else:
        print(ans)


if __name__ == '__main__':
    main()
### BUGGY CODE ###

N,M = map(int,input().split())
*P, = map(int,input().split())
XY = [list(map(int,input().split())) for _ in [0]*M]

E = [[] for _ in [0]*N]
for x,y in XY:
    E[x-1].append(y-1)
    E[y-1].append(x-1)
    
def dist_bfs(N,E,start):
    d = [-1]*N
    d[start] = 0
    q = [start]
    while q:
        i = q.pop()
        di = d[i]
        for j in E[i]:
            if d[j]!=-1:continue
            d[j] = di+1
            q.append(j)
    return d

done = [False]*N
ans = 0
for i in range(N):
    if done[i]:continue
    d = dist_bfs(N,E,i)
    J = set(j for j in range(N) if d[j]>=0)
    PJ = set(P[j]-1 for j in J)
    ans += len(J & PJ)
    for j in J:
        done[j] = True
print(ans)

### FIXED CODE ###

N,M =map(int,input().split())
p = list(map(lambda x:int(x)-1,input().split()))
xy = [list(map(lambda x:int(x)-1,input().split())) for _ in range(M)]
group = [i for i in range(N)]
glist = [[i] for i in range(N)]
def merge(x,y):
    gx = group[x]
    gy = group[y]
    if gx == gy:
        return
    if len(glist[gx])<len(glist[gy]):
        gx,gy = gy,gx
    for y in glist[gy]:
        group[y] = gx
    glist[gx] += glist[gy]
    glist[gy] = []
    return
for x,y in xy:
    merge(x,y)
out = sum([len(set(row) & set(p[g] for g in row)) for row in glist])
print(out)