带权并差集+思考

题意

1
给你两个物体的重量,要你求给出的不同的物体的重量差!带权并差集;

题解

1
只要变量之间具有传递性,都可以用并查集,来进行传递!在合并时最好画张图,用fu,fv进行合并

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;
const int Maxn=200005;
int fa[Maxn];LL val[Maxn];
char s[105];
int (int x)
{
if(fa[x]==x) return x;
int fx=find(fa[x]);
val[x]+=val[fa[x]];
return fa[x]=fx;
}
void unions(int u,int v,LL w)
{
int fu=find(u),fv=find(v);
if(fu!=fv){
fa[fu]=fv;
val[fu]=w+val[v]-val[u];
}
}
int main()
{
int m,n,u,v;LL w;
while(scanf("%d%d",&n,&m) && n && m)
{
memset(val,0,sizeof(val));
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=m;i++)
{
scanf("%s%d%d",s,&u,&v);
if(s[0]=='!')
{
scanf("%lld",&w);
unions(u,v,w);
}
else
{
int fu=find(u),fv=find(v);
if(fu!=fv) printf("UNKNOWNn");
else printf("%lldn",val[u]-val[v]);
}
}
}
return 0;
}