UVAlive6187【带权值并查集】

思路:
利用并查集是显然的。
如何处理权值,这个要想一下。

对于A->B->C->D这个集合,X->Y代表X是Y的祖先,每个点有一个权值num[p]
我们把权值放在最底端,这样主要是方便合并(个人觉得)

首先在同一个集合的X, Y求差值的话直接num[X] - num[Y]就好了

然后合并 Ai, Bj这两个点,分别位于A,B集合,我们找到A集合的根rootA,找到B集合的根rootB,如果输入是 Ai, Bi, w ,我们能知道的是num[Ai] - num[Bi] = w; num[Ai] = num[Bi] + w; 以及 num[rootA] = num[Ai] - num[Ai] => num[rootA] = num[Bi] + w - num[Ai].

关于Find函数,找root就不多说了。

对于路径压缩,也就是对于一个X,要直接和这个集合的root直连,其实自己想一想这个num[]更新也好写,就不多说了。

//#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long LL;
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define mem(a, b) memset(a, b, sizeof(a))

const int Maxn = 1e5 + 10;
int n, m;
int pre[Maxn];
LL num[Maxn];

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

int Find(int x){
    int r = x;
    LL sum = 0;
    while(pre[r] != r){
        sum = sum + num[r];
        r = pre[r];
    }
    int i = x, j;
    LL temp = sum;
    while(pre[i] != r){
        temp = sum - num[i];
        j = pre[i];

        num[i] = sum;
        pre[i] = r;

        sum = temp;
        i = j;
    }
    return r;
}

void Merge(int x, int y, LL w){
    int xx = Find(x);
    int yy = Find(y);
    if(xx != yy){
        pre[xx] = yy;
        num[xx] = num[y] + w - num[x];
    }
}

void solve(){
    char op[5];
    int a, b;
    LL w;
    while(~scanf("%d%d", &n, &m)){
        if(!n && !m) break;
        init();
        while(m--){
            scanf("%s", op);
            if(op[0] == '!'){
                scanf("%d%d%lld", &a, &b, &w);
                Merge(a, b, w);
            }
            else{
                scanf("%d%d", &a, &b);
                int xx = Find(a);
                int yy = Find(b);
                if(xx != yy){
                    puts("UNKNOWN");
                }
                else
                    printf("%lld\n", num[a]-num[b]);
            }
        }
    }
}

int main()
{
    solve();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值