UVALive

来源:互联网 发布:js math.random 1到10 编辑:程序博客网 时间:2024/06/05 06:03

这题比较简单,注意路径压缩即可。


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;}

如有不当之处欢迎指出!

原创粉丝点击