并查集
笔记
例题
洛谷 P2078 朋友
两个并查集,求数量小的个数。
代码
#include <iostream>
using namespace std;
int father[20005],mather[20005];
int ans1,ans2;
int findx(int x,int parent[])
{
int r = x;
while(parent[r]!=r)
{
r=parent[r];
}
return r;
}
void add(int x,int y)
{
int xx,yy;
if(x > 0 && y > 0)
{
xx = findx(x,father);
yy = findx(y,father);
if(xx!=yy)
{
father[xx]=yy;
}
}
else
{
xx = findx(-x,mather);
yy = findx(-y,mather);
if(xx!=yy)
{
mather[xx]=yy;
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
int n,m,p,q;
cin >> n >> m >> p >> q;
for(int i = 1;i<10005;i++)
{
father[i]=i;
mather[i]=i;
}
int a,b;
for(int i = 0;i < p;i++)
{
cin >> a >> b;
add(a,b);
}
for(int i = 0;i < q;i++)
{
cin >> a >> b;
add(a,b);
}
int one1 = findx(1,father);
for(int i = 1;i <= n;i++)
{
if (one1 == findx(i,father))
ans1++;
}
int one2 = findx(1,mather);
for(int i = 1;i <= m;i++)
{
if (one2 == findx(i,mather))
ans2++;
}
int ans = min(ans1,ans2);
cout << ans << endl;
return 0;
}