您的位置:首页 > 其它

LA 3027 并查集

2015-08-24 09:06 246 查看
比较基础的带权并查集,需要注意终止条件是'O'而不是'0'...

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;

const int N = 20001;
const int MOD = 1000;
int f
;
int d
;

void init( int n )
{
for ( int i = 1; i <= n; i++ )
{
f[i] = i;
d[i] = 0;
}
}

void findf( int x )
{
if ( f[x] == x ) return ;
int tx = f[x];
findf(tx);
d[x] += d[tx];
f[x] = f[tx];
}

int main ()
{
int t;
scanf("%d", &t);
while ( t-- )
{
int n;
scanf("%d", &n);
init(n);
char op[2];
while ( scanf("%s", op) != EOF )
{
if ( op[0] == 'O' ) break;
int x, y;
if ( op[0] == 'E' )
{
scanf("%d", &x);
findf(x);
printf("%d\n", d[x]);
}
else
{
scanf("%d%d", &x, &y);
f[x] = y;
d[x] = ( ( int ) abs( x - y ) ) % MOD;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: