在线求助,为啥全部WA
查看原帖
在线求助,为啥全部WA
285961
魏老师楼主2021/3/29 06:21
//树链剖分:轻重链剖分
#include<bits/stdc++.h>
using namespace std;
//树的存储:按数组、边型单链表图式存储 
int first[500005],next[500005],to[500005];
//father[x]x在树中的父亲;
//dep[x]x在树中的深度;
//size[x]x的子树结点数;
//son[x]x的重儿子,即x->son[x]为重边 
int father[500005],dep[500005],size[500005],son[500005];
//top[x]x所在重链的顶部结点;
int top[500005];
void dfs1(int u);//第一次深搜
void dfs2(int u);//第二次深搜  
void lca(int x,int y);//求结点x和结点y的最近公共祖先 

int main()
{
    freopen("in.in","r",stdin);
	freopen("out.out","w",stdout);
    int n,m,s,a,b,num=0;//a->b有一条边,num是边序号 
	cin>>n>>m>>s;//n存储顶点个数 
	for(int i=1;i<n;i++)
	{
		//前插式存储树,注意边序号是唯一的 
		cin>>a>>b;
		++num;
		to[num]=a; 
		next[num]=first[b];
		first[b]=num;
	}
	father[s]=0;dep[0]=0;//根节点初始化
	dfs1(s); 
	top[s]=s;//线段树结点编号初始化 
	dfs2(s);
    for(int i=1;i<=m;i++)
    {
    	int x,y;
    	cin>>x>>y;
    	lca(x,y);//求结点2和结点8的lca 
	}
    return 0;	
} 

void dfs1(int u)
{
	size[u]=1;
	dep[u]=dep[father[u]]+1;
	for(int e=first[u];e;e=next[e])
	{
		father[to[e]]=u;
		dfs1(to[e]);
		size[u]+=size[to[e]];
		//son[u],即u的重儿子初始化为0 
		if(size[to[e]]>size[son[u]]) son[u]=to[e];
	}
}

void dfs2(int u)
{
	if(son[u])//如果有重儿子,重儿子优先,一路到底编号 
	{
		top[son[u]]=top[u];
		dfs2(son[u]); 
	}
	for(int e=first[u];e;e=next[e])//其余轻边遍历
	{
	    if(!top[to[e]])//如果没有搜过 
		{
			top[to[e]]=to[e];
			dfs2(to[e]); 
		}	
	} 
}

void lca(int x,int y)
{
	int fx=top[x],fy=top[y];
	while(fx!=fy)
	{
		if(dep[fx]<dep[fy])//保证fx深度不小于fy的深度 
	    {
		   swap(x,y);swap(fx,fy);
	    }
		x=father[fx];fx=top[x];
	}
	//如果在一条重链上,那么深度小的是lca 
	if(dep[x]>dep[y]) swap(x,y);
	cout<<x<<endl;
}


2021/3/29 06:21
加载中...