您的位置:首页 > 其它

并查集 带压缩路径的版本

2011-09-26 16:12 190 查看
#include <iostream>
using
namespace
std;
typedef
struct
{
int
a,b;
}road;
const
int
MAX=5001;
int
N,M,K;
int
father[MAX];
int
rank[MAX];
road rd[500000];
void
make_set()
{
int
i;
for
(i=1;i<=N;i++)
{
father[i]=i;
rank[i]=0;
}
}
int
find_set(
int
x)
{
if
(x!=father[x])
father[x]=find_set(father[x]);
return
father[x];
}
void
union_set(
int
x,
int
y)
{
x=find_set(x);
y=find_set(y);
if
(x==y)
return
;
if
(rank[x]>rank[y])
father[y]=x;
else
{
father[x]=y;
if
(rank[x]==rank[y])
rank[y]++;
}
}
int
main()
{
cin>>N>>M>>K;
int
i,j;
int
start,end;
int
input;
for
(i=1;i<=M;i++)
{
cin>>start>>end;
rd[i].a=start;
rd[i].b=end;
}
for
(i=1;i<=K;i++)
{
int
cnt=-2;
cin>>input;
make_set();
for
(j=1;j<=M;j++)
{
if
(rd[j].a!=input && rd[j].b!=input)
union_set(rd[j].a,rd[j].b);
}
for
(j=1;j<=N;j++)
{
if
(father[j]==j)
cnt++;
}
cout<<cnt<<endl;
}
return
0;
}
/**************************************************************
Problem: 1325
User: feng345feng
Language: C++
Result: Accepted
Time:800 ms
Memory:5456 kb
****************************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: