好不容易在POJ上找了题并查集,结果被完爆了。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 30010
typedef struct{
int fa;
int tot,dis;//dis是距离其根节点的结点。
}Node;
Node a[N];
void ini()
{
for(int i = 0; i < N; ++i)
{
a[i].fa = i;
a[i].tot = 1;
a[i].dis = 0;
}
}
int fint(int x)
{
int ret;
if(a[x].fa == x)
return x;
ret = fint(a[x].fa);
a[x].dis += a[a[x].fa].dis;
a[x].fa = ret;//数出个数后就能直接将其连在ret上。
return ret;
}
void move()
{
int g,b,x,y;
scanf("%d%d",&g,&b);
x = fint(g); y = fint(b);
a[y].dis = a[x].tot;//x放在y上面。
a[x].tot += a[y].tot;
a[y].fa = x;
}
void cou()
{
int g,b;
scanf("%d",&g);
b = fint(g);
printf("%d\n",a[b].tot - a[g].dis - 1);
}
int main()
{
ini();
char ch;
int m,i;
cin >> m;
for(i = 1; i <= m; ++i)
{
cin >> ch;
if(ch == 'M')
move();
else
cou();
}
return 0;
}
如果真正用栈去写的话,等着栈爆吧。我也借鉴了别人的代码,这里对并栈和查找非常的巧妙。
472

被折叠的 条评论
为什么被折叠?



