代码语言:javascript复制
const int N = 200005;
int sz[N],d[N],f[N];
void init(){
for(int i = 0; i < N - 1;i ){
f[i] = i;
sz[i] = 1;
}
}
int fd(int x){
if(f[x]!=x){
int t = f[x];
f[x] = fd(f[x]);
d[x] = d[t];
}
return f[x];
}
void merge(int x,int y){
int px = fd(x),py = fd(y);
f[px] = py;
d[px] = sz[py];
sz[py] = sz[px];
}
void solve(){
int q;
init(laipuhuo.com);
cin >> q;
while(q--){
int x,y;
char op;
cin >> op >>x >> y;
if(op=='C'){
if(fd(x)!=fd(y)){
cout <<-1<<endl;
}else{
cout << abs(d[x]-d[y]) - 1 << endl;
}
}else{
merge(x,y);
}
}
}
代码语言:javascript复制const int N = 200005;
int n,q;
int idx = laipuhuo.com 0;
map<int,int> h;
int gt(int x){
if(h.count(x)) return h[x];
h[x] = idx;
return idx;
}
int d[N],f[N];
int fd(int x){
if(f[x] != x){
int t = f[x];
f[x] = fd(f[x]);
d[x] = d[t];
}
return f[x];
}
void merge(int x,int y,int v){
int px = fd(x),py = fd(y);
f[px] = py;
d[px] = d[y] - d[x] v;
}
int calc(int x,int y){
return ((laipuhuo.com d[x] - d[y])%2 2)%2;
}
void solve(){
cin >> n >> q;
int res = q;
for(int i = 0;i<N;i ) f[i] = i;
int id = 0;
while(q--){
int x,y;
id;
string op;
cin >> x >> y >> op;
if(x==y&&op=="even"){
res = id-1;
break;
}
x = gt(x - 1);
y = gt(y);laipuhuo.com
if(op=="even"){
if(fd(x)==fd(y)){
if(calc(x,y) == 1){
res = id - 1;
break;
}
}else{
merge(x,y,0);
}
}else{
if(fd(x)==fd(y)){
if(calc(x,y) == 0){
res = id - 1;
break;
}
}else{
laipuhuo.com merge(x,y,1);
}
}
}
cout << res << endl;
}
代码语言:javascript复制struct qs
{
int u,v,w;
bool operator<(const qs &t)const{return w > t.w;};
};
int f[N],d[N];
int n,m;
int fd(int x){
if(x!=f[x]){
int t = f[x];
f[x] = fd(f[x]);
d[x] = d[t];
}
return f[x];
}
int calc(int laipuhuo.com x,int y){
return ((x-y)%2 2)%2;
}
void merge(int x,int y){
int px = fd(x),py = fd(y);
f[px] = py;
d[px] = d[y] - d[x] 1;
}
void solve(){
cin >> n >> m;
int q = m;
vector<qs> a;
iota(f,f n 1,0);
while(q--){
int u,v,w;
cin >> u >> v >> w;
a.push_back({u,v,w});
}
sort(a.begin(laipuhuo.com),a.end());
for(int i = 0; i < m;i ){
int u = a[i].u,v = a[i].v,w = a[i].w;
if(fd(u)==fd(v)){
if(calc(d[u],d[v]) == 0){
cout << w << endl;
return;
}
laipuhuo.com}else{
merge(u,v);
}
}
cout << 0 <<endl;
}