您的位置:首页 > 其它

UVALive - 3027 Corporative Network (并查集)

2017-07-29 14:24 393 查看
这题比较简单,注意路径压缩即可。

AC代码

//#define LOCAL
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn = 20000+5;
int par[maxn], dis[maxn];

void init(int n) {
for(int i = 0; i <= n; i++) {
par[i] = i;
dis[i] = 0;
}
}

int findRoot(int x) {
if(x == par[x]) {
return x;
} else {
int root = findRoot(par[x]);
dis[x] += dis[par[x]];
return par[x] = root;
}
}

int main() {
#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif // LOCAL

int T, n;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
init(n);
char cmd[10];
int x, y;
while(scanf("%s", cmd) == 1 && cmd[0] != 'O') {
char tag = cmd[0];
if(tag == 'E') {
scanf("%d", &x);
findRoot(x);
printf("%d\n", dis[x]);
} else {
scanf("%d%d", &x, &y);
par[x] = y;
dis[x] = abs(x-y) % 1000;
}
}

}
return 0;
}


如有不当之处欢迎指出!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: