#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<string>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<stack>
#include<cmath>
#include<map>
#include<vector>
#define ll long long
#define inf 0x3f3f3f3f
#define bug1 cout<<"bug1"<<endl;
#define bug2 cout<<"bug2"<<endl;
#define bug3 cout<<"bug3"<<endl;
using namespace std;
const int maxn=1e6+5;
int fa[maxn];
int n,m;
int d[maxn];
int _find(int x){
//d[x]+=d[fa[x]];
if(x==fa[x]){
return x;
}
else{
_find(fa[x]);//最后就加了这个就对了
d[x]+=d[fa[x]];
fa[x]=_find(fa[x]);
//d[x]+=d[fa[x]];
}
return fa[x];
}
void conbine(int u,int v,int w){
int rootu=_find(u);
int rootv=_find(v);
if(rootu==rootv)return;
fa[rootv]=rootu;
d[rootv]=w;
}
void init(){
memset(d,0,sizeof(d));
for(int i=1;i<=n;++i){
fa[i]=i;
//root[i]=i;
}
}
int main(){
scanf("%d%d",&n,&m);
init();
char c[3];
for(int i=1;i<=m;++i){
scanf("%s",&c);
if(c[0]=='C'){
int a;
scanf("%d",&a);
_find(a);
cout<<d[a]<<'\n';
}
else {
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
conbine(u,v,w);
}
/*
for(int i=1;i<=n;++i){
cout<<i<<' '<<fa[i]<<endl;
}*/
/*
for(int i=1;i<=n;++i){
cout<<d[i]<<' ';
}cout<<endl;*/
}
}
并查集及优化
最新推荐文章于 2022-07-16 18:27:22 发布