1529: [POI2005]ska Piggy banks
Time Limit: 5 Sec Memory Limit: 64 MB[Submit][Status][Discuss]
Description
Input
Output
Sample Input
2
1
2
4
Sample Output
2
In the foregoing example piggy banks 1 and 4 have to be smashed.
HINT
Source
#include <bits/stdc++.h>
using namespace std;
int n, vis[1000005], fa[1000005], ans;
int find( int x ){ return x == fa[x] ? x : fa[x] = find( fa[x] ); }
int main(){
scanf( "%d", &n );
for( int i = 1; i <= n; i++ ) fa[i] = i;
for( int i = 1, x; i <= n; i++ ) scanf( "%d", &x ), fa[find(x)] = find(i);
for( int i = 1; i <= n; i++ ) if( vis[find(i)] ) continue; else vis[find(i)] = 1, ans++;
cout<<ans<<endl;
return 0;
}