Time Limit: 5 Sec Memory Limit: 64 MB
Submit: 1062 Solved: 494
[Submit][Status][Discuss]
Description
Byteazar 有 N 個小豬存錢罐. 每個存錢罐只能用鑰匙打開或者砸開. Byteazar 已經把每個存錢罐的鑰匙放到了某些存錢罐裏. Byteazar 現在想買一臺汽車於是要把所有的錢都取出來. 他想盡量少的打破存錢罐取出所有的錢,問最少要打破多少個存錢罐.
Input
第一行一個整數 N (1 <= N <= 1.000.000) – 表示存錢罐的總數. 接下來每行一個整數,第 i+1行的整數代表第i個存錢罐的鑰匙放置的存錢罐編號.
Output
一個整數表示最少打破多少個存錢罐.
Sample Input
4
2
1
2
4
Sample Output
2
In the foregoing example piggy banks 1 and 4 have to be smashed.
HINT
Source
Sol:無腦並查集
#include<cstdio>
#define N 1000005
inline int in(int x=0,char ch=getchar()){while(ch>'9'||ch<'0') ch=getchar();
while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();return x;}
int n,x,f1,f2,ans;int f[N];
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
int main(){
n=in();
for(int i=1;i<=n;i++) f[i]=i;
for(int i=1;i<=n;i++) x=in(),f1=find(x),f2=find(i),f[f1]=f2;
for(int i=1;i<=n;i++) ans+=f[i]==i;
printf("%d\n",ans);
return 0;
}