1529: [POI2005]ska Piggy banks
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 1472 Solved: 736
[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
2
1
2
4
Sample Output
2
In the foregoing example piggy banks 1 and 4 have to be smashed.
In the foregoing example piggy banks 1 and 4 have to be smashed.
HINT
Source
这道题就是求最后缩完点后有多少个点入度为0
但是这样的空间有可能会超,卡一下的话应该也可以过
我们可以用并查集来维护最后有多少个点父亲是自己即可
#include <bits/stdc++.h>
#define ll long long
using namespace std;
inline int read(){
int x=0;int f=1;char ch=getchar();
while(!isdigit(ch)) {if(ch=='-') f=-1;ch=getchar();}
while(isdigit(ch)) {x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int MAXN=1e6+10;
int f[MAXN],ans;
inline int getfather(int x){
return f[x]==x?x:f[x]=getfather(f[x]);
}
int main(){
int n=read();
for(int i=1;i<=n;i++){
f[i]=i;
}
for(int i=1;i<=n;i++){
int xx=read();
int fx=getfather(i);int fy=getfather(xx);
f[fy]=fx;
}
for(int i=1;i<=n;i++){
if(f[i]==i) ans++;
}
cout<<ans<<endl;
return 0;
}