/* -*- coding: utf-8 -*- * * 2563.cc: No.2563 色ごとのグループ - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 200000; /* typedef */ typedef vector vi; struct UFT { vector links, ranks, sizes; UFT() {} void init(int n) { links.resize(n); for (int i = 0; i < n; i++) links[i] = i; ranks.assign(n, 1); sizes.assign(n, 1); } int root(int i) { int i0 = i; while (links[i0] != i0) i0 = links[i0]; return (links[i] = i0); } int rank(int i) { return ranks[root(i)]; } int size(int i) { return sizes[root(i)]; } bool same(int i, int j) { return root(i) == root(j); } int merge(int i0, int i1) { int r0 = root(i0), r1 = root(i1), mr; if (r0 == r1) return r0; if (ranks[r0] == ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; ranks[r0]++; mr = r0; } else if (ranks[r0] > ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; mr = r0; } else { links[r0] = r1; sizes[r1] += sizes[r0]; mr = r1; } return mr; } }; /* global variables */ int cs[MAX_N]; vi cvs[MAX_N]; UFT uft; /* subroutines */ /* main */ int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { scanf("%d", cs + i), cs[i]--; cvs[cs[i]].push_back(i); } uft.init(n); for (int i = 0; i < m; i++) { int u, v; scanf("%d%d", &u, &v); u--, v--; if (cs[u] == cs[v]) uft.merge(u, v); } int cnt = 0; for (int c = 0; c < n; c++) { vi &cv = cvs[c]; int l = cv.size(); for (int i = 1; i < l; i++) if (! uft.same(cv[0], cv[i])) { cnt++; uft.merge(cv[0], cv[i]); } } printf("%d\n", cnt); return 0; }