Problem:
Score : 400 points

Problem Statement

We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N.
We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M).
AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized:

Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}.

Find the maximum possible number of i such that p_i = i after operations.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

p is a permutation of integers from 1 through N.

1 ≤ x_j,y_j ≤ N

x_j ≠ y_j

If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
p_1 p_2 .. p_N
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the maximum possible number of i such that p_i = i after operations.

Sample Input 1

5 2
5 3 1 4 2
1 3
5 4

Sample Output 1

2

If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2.

Sample Input 2

3 2
3 2 1
1 2
2 3

Sample Output 2

3

If we perform the operation by, for example, choosing j=1, j=2, j=1 in this order, p becomes 1 2 3, which is obviously optimal.
Note that we may choose the same j any number of times.

Sample Input 3

10 8
5 3 6 8 7 10 9 1 2 4
3 1
4 1
5 9
2 5
6 5
3 5
8 9
7 9

Sample Output 3

8

Sample Input 4

5 1
1 2 3 4 5
1 5

Sample Output 4

5

We do not have to perform the operation.

Solution in Rust (1.15.1) (judge verdict: Time Limit Exceeded)

use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::str::FromStr;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = AtRead::from(i);
    let (n, m) = i.read2::<usize, usize>();
    let mut p = i.read_vec::<usize>(n);
    let mut xys = Vec::new();
    for _ in 0..m {
        let xy = i.read2::<usize, usize>();
        xys.push((xy.0 - 1, xy.1 - 1));
    }
    for p in p.iter_mut() {
        *p -= 1;
    }

    writeln!(o, "{}", solve(&p, &xys)).unwrap();
}
fn solve(p: &[usize], xy: &[(usize, usize)]) -> usize {
    let mut visit = vec![false; p.len()];
    let mut edges = vec![Vec::new(); p.len()];
    let mut result = 0;

    for &xy in xy {
        edges[xy.0].push(xy.1);
        edges[xy.1].push(xy.0);
    }
    let mut q = Vec::new();
    let mut idxs = HashSet::new();
    for i in 0..p.len() {
        if visit[i] {
            continue;
        }
        visit[i] = true;
        q.push(i);
        idxs.insert(i);
        while let Some(i0) = q.pop() {
            for &i1 in &edges[i0] {
                if visit[i1] {
                    continue;
                }
                visit[i1] = true;
                q.push(i1);
                idxs.insert(i1);
            }
        }
        for &idx in &idxs {
            if idxs.contains(&p[idx]) {
                result += 1;
            }
        }
        idxs.clear();
    }
    result
}

mod utils {
    #![allow(dead_code)]
    use super::*;
    use std::ops::*;

    pub struct AtRead<R: BufRead> {
        r: R,
        s: String,
    }

    macro_rules! fn_read {
        {$f:ident($($v:ident: $t:ident),*)} => {
            pub fn $f<$($t: FromStr),*>(&mut self) -> ($($t),*) {
                let i = &mut self.read_line().split(' ');
                $(
                    let $v = next(i);
                )*
                ($($v),*)
            }
        };
    }

    impl<R: BufRead> AtRead<R> {
        pub fn from(r: R) -> Self {
            AtRead {
                r: r,
                s: String::new(),
            }
        }
        pub fn read_line(&mut self) -> &str {
            self.s.clear();
            self.r.read_line(&mut self.s).unwrap();
            self.s.trim()
        }

        pub fn read<T: FromStr>(&mut self) -> T {
            self.read_line().parse().ok().unwrap()
        }
        fn_read! { read2(v1: T1, v2: T2) }
        fn_read! { read3(v1: T1, v2: T2, v3: T3) }
        fn_read! { read4(v1: T1, v2: T2, v3: T3, v4: T4) }
        fn_read! { read5(v1: T1, v2: T2, v3: T3, v4: T4, v5: T5) }

        pub fn read_vec<T: FromStr>(&mut self, n: usize) -> Vec<T> {
            self.read_line()
                .split(' ')
                .take(n)
                .map(|x| x.parse().ok().unwrap())
                .collect()
        }
        pub fn read_array<A: AsMut<[T]> + Default, T: FromStr>(&mut self) -> A {
            let mut a: A = Default::default();
            {
                let a: &mut [T] = a.as_mut();
                let i = &mut self.read_line().split(' ');
                for n in 0..a.len() {
                    a[n] = next(i);
                }
            }
            a
        }
    }

    fn next<'a, T: FromStr, I: std::iter::Iterator<Item = &'a str>>(i: &mut I) -> T {
        i.next().unwrap().parse().ok().unwrap()
    }

    #[derive(Debug, Clone, Copy)]
    pub struct ModInt(pub usize);

    const MOD_BASE: usize = 1000000007;
    const MOD_INV_POW: usize = 1000000005;

    impl ModInt {
        pub fn new(n: usize) -> Self {
            ModInt(n % MOD_BASE)
        }
        pub fn pow(self, mut exp: usize) -> Self {
            let mut b = self;
            let mut r = ModInt(1);
            while exp != 0 {
                if exp % 2 == 1 {
                    r *= b;
                }
                exp /= 2;
                b = b * b;
            }
            r
        }
        pub fn inverse_element(self) -> Self {
            self.pow(MOD_INV_POW)
        }
    }

    macro_rules! ModInt_op {
        (($ot:ident, $f:ident), ($ot_a:ident, $f_a:ident), $($rhs:ty, $e:expr,)*) => {
            $(
            impl $ot<$rhs> for ModInt {
                type Output = Self;
                fn $f(self, rhs: $rhs) -> Self {
                    Self::new(($e)(self, rhs))
                }
            }
            impl $ot_a<$rhs> for ModInt {
                fn $f_a(&mut self, rhs: $rhs) {
                    *self = Self::new(($e)(*self, rhs))
                }
            }
            )*
        }
    }

    ModInt_op!(
        (Add, add),
        (AddAssign, add_assign),
        ModInt,
        |l: ModInt, r: ModInt| l.0 + r.0,
        usize,
        |l: ModInt, r: usize| l.0 + r,
    );

    ModInt_op!(
        (Mul, mul),
        (MulAssign, mul_assign),
        ModInt,
        |l: ModInt, r: ModInt| l.0 * r.0,
        usize,
        |l: ModInt, r: usize| l.0 * r,
    );

    ModInt_op!(
        (Sub, sub),
        (SubAssign, sub_assign),
        ModInt,
        |l: ModInt, r: ModInt| MOD_BASE + l.0 - r.0,
        usize,
        |l: ModInt, r: usize| MOD_BASE + l.0 - r,
    );

    // std::cmp::Reverseと同じ
    #[derive(PartialEq, Eq)]
    pub struct RevCmp<T>(pub T);

    impl<T: PartialOrd> PartialOrd for RevCmp<T> {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            other.0.partial_cmp(&self.0)
        }
    }
    impl<T: Ord> Ord for RevCmp<T> {
        fn cmp(&self, other: &Self) -> Ordering {
            other.0.cmp(&self.0)
        }
    }

    pub struct PascalsTriangle<T> {
        buf: Vec<T>,
        n: usize,
    }

    impl<T: One> PascalsTriangle<T> {
        pub fn new(n: usize) -> Self {
            let mut s = PascalsTriangle {
                buf: vec![T::one()],
                n: 1,
            };
            while s.n <= n {
                let i = s.buf.len() - s.n;
                s.buf.push(T::one());
                for m in 1..s.n {
                    let v = s.buf[i + m - 1] + s.buf[i + m];
                    s.buf.push(v);
                }
                s.buf.push(T::one());
                s.n += 1;
            }
            s
        }
        pub fn get(&mut self, n: usize, m: usize) -> T {
            debug_assert!(n <= self.n);
            debug_assert!(m <= n);
            self.buf[n * (n + 1) / 2 + m]
        }
    }

    pub struct PascalsTriangleIter<T> {
        buf: Vec<T>,
    }
    impl<T: One> PascalsTriangleIter<T> {
        pub fn new(n: usize) -> Self {
            let mut s = PascalsTriangleIter {
                buf: Vec::with_capacity(n + 1),
            };
            for _ in 0..n + 1 {
                s.next();
            }
            s
        }
        pub fn next(&mut self) {
            for i in (1..self.buf.len()).rev() {
                self.buf[i] = self.buf[i] + self.buf[i - 1];
            }
            self.buf.push(T::one());
        }
        pub fn get(&self) -> &[T] {
            &self.buf
        }
    }

    pub struct ModIntFacts {
        f: Vec<ModInt>,
        rf: Vec<ModInt>,
    }
    impl ModIntFacts {
        pub fn new(n: usize) -> Self {
            let mut s = ModIntFacts {
                f: vec![ModInt(0); n + 1],
                rf: vec![ModInt(0); n + 1],
            };

            let v = ModInt(1);
            s.f[0] = v;
            for i in 1..n + 1 {
                s.f[i] = s.f[i - 1] * i;
            }
            s.rf[n] = s.f[n].inverse_element();
            for i in (1..n + 1).rev() {
                s.rf[i - 1] = s.rf[i] * i;
            }
            s
        }
        pub fn fact(&self, n: usize) -> ModInt {
            self.f[n]
        }
        pub fn comb(&self, n: usize, c: usize) -> ModInt {
            self.f[n] * self.rf[c] * self.rf[n - c]
        }
    }

    pub trait Zero: Add<Output = Self> + Sized + Copy {
        fn zero() -> Self;
    }
    pub trait One: Zero {
        fn one() -> Self;
    }

    macro_rules! impl_zero {
        ($t:ty, $e:expr) => {
            impl Zero for $t {
                fn zero() -> Self {
                    $e
                }
            }
        }
    }
    macro_rules! impl_one {
        ($t:ty, $e1:expr, $e0:expr) => {
            impl One for $t {
                fn one() -> Self {
                    $e1
                }
            }
            impl_zero!($t, $e0);
        };
    }

    impl_one!(usize, 1, 0);
    impl_one!(u32, 1, 0);
    impl_one!(i32, 1, 0);
    impl_one!(f64, 1.0, 0.0);
    impl_one!(ModInt, ModInt(1), ModInt(0));

    pub trait BinarySearchExt<T> {
        fn lower_bound_by<F: Fn(&T) -> bool>(&self, f: F) -> usize;
        fn lower_bound(&self, x: &T) -> usize;
        fn upper_bound(&self, x: &T) -> usize;
    }
    impl<T: Ord> BinarySearchExt<T> for [T] {
        fn lower_bound_by<F: Fn(&T) -> bool>(&self, f: F) -> usize {
            let mut low = 0;
            let mut high = self.len();
            while low < high {
                let mid = (low + high) / 2;
                if f(&self[mid]) {
                    high = mid;
                } else {
                    low = mid + 1;
                }
            }
            low
        }
        fn lower_bound(&self, x: &T) -> usize {
            self.lower_bound_by(|y| x <= y)
        }
        fn upper_bound(&self, x: &T) -> usize {
            self.lower_bound_by(|y| x < y)
        }
    }

    pub trait AtSliceExt<T> {
        fn rotate(&mut self, mid: usize);
    }
    impl<T> AtSliceExt<T> for [T] {
        fn rotate(&mut self, mid: usize) {
            {
                let (l, r) = self.split_at_mut(mid);
                l.reverse();
                r.reverse();
            }
            self.reverse()
        }
    }

}