您的位置:首页 > 其它

bzoj1529: [POI2005]ska Piggy banks

2016-06-12 17:17 399 查看
传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1529

题目大意:Byteazar 有 N 个小猪存钱罐. 每个存钱罐只能用钥匙打开或者砸开. Byteazar 已经把每个存钱罐的钥匙放到了某些存钱罐里. Byteazar 现在想买一台汽车于是要把所有的钱都取出来. 他想尽量少的打破存钱罐取出 所有的钱,问最少要打破多少个存钱罐.

题解:并查集

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define maxn 1000005
using namespace std;
int n,tot,ans;
int fa[maxn];
int read()
{
int x=0; char ch; bool bo=0;
while (ch=getchar(),ch<'0'||ch>'9') if (ch=='-') bo=1;
while (x=x*10+ch-'0',ch=getchar(),ch>='0'&&ch<='9');
if (bo) return -x; return x;
}
int find(int x)
{
if (fa[x]!=x) fa[x]=find(fa[x]);
return fa[x];
}
int main()
{
n=read();
for (int i=1; i<=n; i++) fa[i]=i;
for (int i=1; i<=n; i++)
{
int x=read();
int q=find(i),p=find(x);
if (q!=p) fa[q]=p;
}
for (int i=1; i<=n; i++) if (fa[i]==i) ans++;
printf("%d\n",ans);
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: