0分树剖lca+并查集 玄棺
查看原帖
0分树剖lca+并查集 玄棺
777848
superkkkeee楼主2024/8/14 21:06

只过了hack

玄棺!!!

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,m,T;
struct nod
{
	int u,v,w;
}a[50001];
vector<int> p[30001];
int son[30001];
int siz[30001];
int fa[30001];
int f[30001];
int top[30001];
int dep[30001];
int w[50001];
bool vis[30001];
int cnt;
int find(int x)
{
	if(fa[x]==x) return x;
	fa[x]=find(fa[x]);
	return fa[x];
}
void add(int x,int y)
{
	int xx=find(x);
	int yy=find(y);
	if(xx==yy) return;
	if(xx>yy) swap(xx,yy);
	f[yy]=xx;
}
bool cmp(nod x,nod y)
{
	return x.w>y.w;
}
void dfs(int x)
{
	siz[x]=1;
	dep[x]=dep[f[x]]+1;
	vis[x]=1;
	for(int xx:p[x])
	{
		if(xx==f[x]) continue;
		f[xx]=x;
		dfs(xx);
		siz[x]+=siz[xx];
		if(son[x]==0||siz[xx]>siz[son[x]]) son[x]=xx;
	}
}
void ds(int x,int tp)
{
	top[x]=tp;
	if(son[x]==0) return;
	ds(son[x],tp);
	for(int xx:p[x])
	{
		if(xx==f[x]||xx==son[x]) continue;
		ds(xx,xx);
	} 
}
int lca(int x,int y)
{
    while(top[x]!=top[y])
    {
    	if(dep[top[x]]>=dep[top[y]]) x=f[top[x]];
        else y=f[top[y]];
	}
	if(dep[x]<dep[y]) return x;
    return y;
}
void hs()
{
	sort(a+1,a+1+m,cmp);
	for(int i=1;i<=m;i++)
    {
        int xx=find(a[i].u);
		int yy=find(a[i].v);
        if(xx!=yy)
        {
            w[++cnt]=a[i].w;
            fa[cnt]=fa[xx]=fa[yy]=cnt;
			p[xx].push_back(cnt); p[cnt].push_back(xx);
			p[yy].push_back(cnt); p[cnt].push_back(yy);
        }
    }
	for(int i=1;i<=cnt;i++)
	{
		if(!vis[i])
		{
			int q=find(i);
			dfs(q);
			ds(q,q);
		}
	}
}
signed main()
{
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin>>n>>m;
	cnt=n;
	for(int i=1;i<=n;i++) fa[i]=i;
	for(int i=1;i<=m;i++)
	{
		cin>>a[i].u>>a[i].v>>a[i].w;
	}
	hs();
	cin>>T;
	while(T--)
	{
		int x,y;
		cin>>x>>y;
		int xx=find(x);
		int yy=find(y);
		if(xx!=yy) 
		{
			cout<<"-1"<<'\n';
			continue;
		}
		int q=lca(xx,yy);
		cout<<w[q]<<'\n';
	}
	return 0;
}
2024/8/14 21:06
加载中...