按秩合并+最大生成树求吊
查看原帖
按秩合并+最大生成树求吊
754467
f_hxr_楼主2023/9/30 17:45

rt

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL maxn=1e5+7;
LL N,M,QWQ,cnt1;
LL f[maxn],dep[maxn],up[maxn];
struct Edge{LL u,v,w;}e[maxn];
void add(LL u,LL v,LL w)
{e[++cnt1].u=u;e[cnt1].v=v;e[cnt1].w=w;}
int cmp(Edge x,Edge y){return x.w>y.w;}
LL getf(LL V){
	if(f[V]==V)return V;
	return getf(f[V]);
}
void Merge(LL X,LL Y,LL W){
	X=getf(X);Y=getf(Y);
	if(dep[X]>dep[Y])swap(X,Y);
	dep[Y]+=dep[X];
	f[X]=Y;up[X]=W;
}
LL CCF(LL u,LL v){
	LL ret=1145141919810;
	while(f[v]!=v)
		ret=min(ret,up[v]),v=f[v];
	while(f[u]!=u)
		ret=min(ret,up[u]),u=f[u];
	return ret;
}
int main(){
	scanf("%lld%lld",&N,&M);
	for(int i=1;i<=N;i++)f[i]=i,dep[i]=1;
	for(int i=1;i<=M;i++)
	{LL x,y,z;cin>>x>>y>>z;add(x,y,z);}
	sort(e+1,e+M+1,cmp);
	for(int i=1;i<=M;i++){
		LL U=e[i].u,V=e[i].v;
		if(getf(U)==getf(V))continue;
		Merge(U,V,e[i].w);
	}
	cin>>QWQ;
	while(QWQ--){
		LL x,y;
		scanf("%lld%lld",&x,&y);
		if(getf(x)!=getf(y)){puts("-1");continue;}
		LL ans=CCF(x,y);
		printf("%lld\n",ans);
	}
	return 0;
}
2023/9/30 17:45
加载中...