思路:
利用并查集是显然的。
如何处理权值,这个要想一下。
对于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;
}