您的位置:首页 > 其它

UVALive 3027 Corporative Network

2013-08-17 08:07 218 查看
并查集,模板题,感觉见过几次这类题。每次写都要重新推一遍,老了,记不住了。

两种操作,E I 询问I到其根节点的距离,I I J 把I的父节点设为J,输入O结束,是O不是0...

用d[x]来表示x到根的距离,d[x] = myabs(a - b) % 1000 - d[a] + d[b]的意思就是a的根x 到b的根y 的距离为 ab间的距离 减去 a到x的距离 再加上b到y的距离。好好理解下,画画图。然后在find里写的就是模板,慢慢理解,必须记住!

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<string>
#include<queue>
#include<cmath>
///LOOP
#define REP(i, n) for(int i = 0; i < n; i++)
#define FF(i, a, b) for(int i = a; i < b; i++)
#define FFF(i, a, b) for(int i = a; i <= b; i++)
#define FD(i, a, b) for(int i = a - 1; i >= b; i--)
#define FDD(i, a, b) for(int i = a; i >= b; i--)
///INPUT
#define RI(n) scanf("%d", &n)
#define RII(n, m) scanf("%d%d", &n, &m)
#define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k)
#define RIV(n, m, k, p) scanf("%d%d%d%d", &n, &m, &k, &p)
#define RV(n, m, k, p, q) scanf("%d%d%d%d%d", &n, &m, &k, &p, &q)
#define RFI(n) scanf("%lf", &n)
#define RFII(n, m) scanf("%lf%lf", &n, &m)
#define RFIII(n, m, k) scanf("%lf%lf%lf", &n, &m, &k)
#define RFIV(n, m, k, p) scanf("%lf%lf%lf%lf", &n, &m, &k, &p)
#define RS(s) scanf("%s", s)
///OUTPUT
#define PN printf("\n")
#define PI(n) printf("%d\n", n)
#define PIS(n) printf("%d ", n)
#define PS(s) printf("%s\n", s)
#define PSS(s) printf("%s ", n)
///OTHER
#define pb(x) push_back(x)
#define CLR(a, b) memset(a, b, sizeof(a))
#define CPY(a, b) memcpy(a, b, sizeof(b))
#define display(A, n, m) {REP(i, n){REP(j, m)PIS(A[i][j]);PN;}}

using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int MOD = 100000000;
const int INFI = 1e9 * 2;
const LL LINFI = 1e17;
const double eps = 1e-6;
const double pi = acos(-1.0);
const int N = 22222;
const int M = 55;
const int move[8][2] = {0, 1, 0, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1};

int f
, d
;

int myabs(int x){return x > 0 ? x : -x;}

int find(int x)
{
if(x == f[x])return x;
int tmp = f[x];
f[x] = find(f[x]);
d[x] += d[tmp];
return f[x];
}

int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);

int t, n, a, b, x, y;
char s[2];
RI(t);
while(t--)
{
RI(n);
REP(i, n + 1)f[i] = i, d[i] = 0;
while(RS(s), s[0] != 'O')
{
if(s[0] == 'E')
{
RI(a);
find(a);
PI(d[a]);
}
else
{
RII(a, b);
x = find(a);
y = find(b);
if(x != y)
{
f[x] = y;
d[x] = myabs(a - b) % 1000 - d[a] + d[b];
}
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  UVALive