树剖lca 5分,求助
查看原帖
树剖lca 5分,求助
112557
UhhhQQQU楼主2020/6/17 22:02

测试点情况:1A 1WA 其余TLE

树剖lca为什么会T啊???

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=10010,M=50010;
int n,m,q;
struct path{
	int u,v,w;
	bool operator <(const path &a)const
	{
		return w>a.w;
	}
}p[M];
int fa[N];
int find(int a)
{
	if(a==fa[a])
		return a;
	else
		return fa[a]=find(fa[a]);
}
struct edge{
	int nxt,go,val;
}e[N*2];
int head[N],cnt;
void add(int u,int v,int w){e[++cnt]=(edge){head[u],v,w},head[u]=cnt;}
int a[N];
int dep[N],sz[N],son[N],ff[N];
int id[N],rid[N],top[N],tot;
void dfs1(int u,int f)
{
	ff[u]=f;
	dep[u]=dep[f]+1;
	sz[u]=1;
	for(int i=head[u];i;i=e[i].nxt)
	{
		int v=e[i].go;
		if(v==f)
			continue;
		dfs1(v,u);
		a[v]=e[i].val;
		sz[u]+=sz[v];
		if(sz[v]>sz[son[u]])
			son[u]=v;
	}
}
void dfs2(int u,int tp)
{
	id[u]=++tot;
	rid[tot]=u;
	top[u]=tp;
	if(son[u])
		dfs2(son[u],tp);
	for(int i=head[u];i;i=e[i].nxt)
	{
		int v=e[i].go;
		if(v==ff[u]||v==son[u])
			continue;
		dfs2(v,v);
	}
}
int xds[N*4];
#define ls (k<<1)
#define rs (k<<1|1)
#define lson ls,l,mid
#define rson rs,mid+1,r
void pushup(int k)
{
	xds[k]=min(xds[ls],xds[rs]);
}
void build(int k,int l,int r)
{
	if(l==r)
	{
		xds[k]=a[rid[l]];
		return ;
	}
	int mid=(l+r)>>1;
	build(lson),build(rson);
	pushup(k);
}
int query(int k,int l,int r,int x,int y)
{
	if(x<=l&&r<=y)
		return xds[k];
	int mid=(l+r)>>1,ret=0x3f3f3f3f;
	if(x<=mid)
		ret=min(ret,query(lson,x,y));
	if(y>mid)
		ret=min(ret,query(rson,x,y));
	return ret;
}
int qjmin(int x,int y)
{
	int ret=0x3f3f3f3f;
	while(top[x]!=top[y])
	{
		if(dep[top[x]]<dep[top[y]])
			swap(x,y);
		ret=min(ret,query(1,1,n,id[top[x]],id[x]));
		x=fa[top[x]];
	}
	if(dep[x]<dep[y])
		swap(x,y);
	ret=min(ret,query(1,1,n,id[y]+1,id[x]));
	return ret;
}
void read()
{
	scanf("%d %d",&n,&m);
	for(int i=1;i<=m;i++)
		scanf("%d %d %d",&p[i].u,&p[i].v,&p[i].w);
}
void kruskal()
{
	sort(p+1,p+1+m);
	int cnt=0;
	for(int i=1;i<=n;i++)
		fa[i]=i;
	for(int i=1;i<=m;i++)
	{
		if(cnt==n-1)
			break;
		int fx=find(p[i].u),fy=find(p[i].v);
		if(fx!=fy)
		{
			++cnt;
			fa[fx]=fy;
			add(p[i].u,p[i].v,p[i].w);
			add(p[i].v,p[i].u,p[i].w);
		}
	}
}
void treepou()
{
	a[1]=0x3f3f3f3f;
	dfs1(1,0);
	dfs2(1,1);
	build(1,1,n);
	int q;
	scanf("%d",&q);
	while(q--)
	{
		int x,y;
		scanf("%d %d",&x,&y);
		int fx=find(x),fy=find(y);
		if(fx!=fy)
			printf("-1\n");
		else
			printf("%d\n",qjmin(x,y));
	}
}
int main()
{
	read();
	kruskal();
	treepou();
	return 0;
}
2020/6/17 22:02
加载中...