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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章