Submission #8408572
Source Code Expand
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define REP(i,n) for(long long i=0;i<n;++i)
#define REPP(i,m,n) for(long long i=m;i<n;++i)
#define rep(i,n) for(long long i = n-1;i>=0;--i)
#define repp(i,n,m) for(long long i = n-1; i >= m; --i)
#define ALL(N) (N.begin(),N.end())
#define de cout << "line : " << __LINE__ << " debug" << endl;
#define pb push_back
#define pq priority_queue
#define Dcout(N) cout << setprecision(20) << N << endl
constexpr long long INF = 2147483647;
constexpr long long INFF = 9223372036854775807;
struct UnionFind{
vector<int> par,r;
//はじめに全てが根であるとしておく
UnionFind(int N):par(N),r(N,1){iota(par.begin(),par.end(),0);}
int root(int x){//根に当たるまで再帰で探す
if(par[x] == x) return x;
else return par[x] = root(par[x]);
}
bool same(int x,int y){//つながっているかどうか判定
return par[x] == par[y];
}
int size(int x){ //根の大きさを判定する
return r[root(x)];
}
void unite(int x, int y){//根が同じでなかったらつなげる
x = root(x), y = root(y);
if(x == y) return;
if(r[x] < r[y]) swap(x,y); //値を小さいほうを根にする
r[x] += r[y];
par[y] = x;
return;
}
};
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N,M;cin >> N >> M;
int P[N];
REP(i,N){
cin >> P[i];--P[i];
}
UnionFind UF(N);
int x,y;
REP(i,M){
cin >> x >> y;
--x;--y;
if(x > y) swap(x,y);
UF.unite(x,y);
}
int ans = 0;
REP(i,N){
UF.root(P[i]);UF.root(i);
if(UF.same(P[i],i)){;
ans++;
}
}
cout << ans << endl;
}
Submission Info
Submission Time |
|
Task |
D - Equals |
User |
rat |
Language |
C++14 (GCC 5.4.1) |
Score |
400 |
Code Size |
1848 Byte |
Status |
AC |
Exec Time |
29 ms |
Memory |
1408 KB |
Judge Result
Set Name |
Sample |
All |
Score / Max Score |
0 / 0 |
400 / 400 |
Status |
|
|
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 |
1 ms |
256 KB |
0_001.txt |
AC |
1 ms |
256 KB |
0_002.txt |
AC |
1 ms |
256 KB |
0_003.txt |
AC |
1 ms |
256 KB |
1_004.txt |
AC |
15 ms |
256 KB |
1_005.txt |
AC |
26 ms |
1408 KB |
1_006.txt |
AC |
29 ms |
1408 KB |
1_007.txt |
AC |
1 ms |
256 KB |
1_008.txt |
AC |
1 ms |
256 KB |
1_009.txt |
AC |
1 ms |
256 KB |
1_010.txt |
AC |
1 ms |
256 KB |
1_011.txt |
AC |
1 ms |
256 KB |
1_012.txt |
AC |
1 ms |
256 KB |
1_013.txt |
AC |
1 ms |
256 KB |
1_014.txt |
AC |
2 ms |
256 KB |
1_015.txt |
AC |
1 ms |
256 KB |
1_016.txt |
AC |
1 ms |
256 KB |
1_017.txt |
AC |
1 ms |
256 KB |
1_018.txt |
AC |
14 ms |
256 KB |
1_019.txt |
AC |
10 ms |
1408 KB |
1_020.txt |
AC |
10 ms |
1408 KB |
1_021.txt |
AC |
10 ms |
1408 KB |
1_022.txt |
AC |
29 ms |
1408 KB |