跳到正文

题解

题解 P3884 【[JLOI2009]二叉树问题】

dessert约 3 分钟
原文
文章信息与版本

文章信息

发布
2018年8月14日
收录
2026年7月16日
更新
2026年11月16日
篇幅
约 3 分钟
获赞
56
题目
P3884

版本

  1. v1当前

思路

只要求出最近公共祖先,什么都好写,详细请看代码。自认为比题解的lca简单一点QWQ。


代码

C++
#include<bits/stdc++.h>
using namespace std;
struct node{
	int father;  //爸爸
	int left;    //左儿子
	int right;   //右儿子
	int deep;    //深度
	int data;    //记录节点走过没
}a[10001];
int sum[101];
int lca(int x,int y){      //最最重要!!!求最近公共祖先
	a[x].data=1;           //把x的节点记录已走过
	while(a[x].father!=0){ //遍历至根节点
		x=a[x].father;     //更新遍历爸爸
		a[x].data=1;       //记录已走过
	}
	while(a[y].data!=1){   //遍历至x节点已走过的节点,找到最近公共祖先
		y=a[y].father;
	}
	return y;
}
int main(){
	int n,x,y,s,t,maxx=1;
	cin>>n;
	a[1].deep=1;    //根节点的深度为1
	a[1].father=0;  //根节点没有爸爸
	for(int i=1;i<n;i++){
		cin>>x>>y;
		if(a[x].left==0)    //这个节点是否有左儿子
		   a[x].left=y;     //变成左儿子
		else                //变成右儿子
		   a[x].right=y;
		a[y].father=x;
		a[y].deep=a[x].deep+1;   //更新深度
		if(a[y].deep>maxx)       //求出最大深度,第一个问题完成
		   maxx=a[y].deep;
	}
	cin>>s>>t;
	int f=lca(s,t),num=0,num1=0;
	while(s!=f){                //记录s到最近公共祖先有多少条边
		s=a[s].father;
		num++;
	}
	num*=2;   //结点间距离的定义:由结点向根方向(上行方向)时的边数×2,
	while(t!=f){               //记录t到最近公共祖先有多少条边
		t=a[t].father;
		num1++;
	}
	for(int i=1;i<=n;i++)      //把每一个深度有多少个节点记录
	    sum[a[i].deep]++;
	sort(sum+1,sum+1+100);
	cout<<maxx<<endl<<sum[100]<<endl<<num+num1; //sum[100]是最大的宽度节点个数
	return 0;
}


------------
拒绝抄袭,共建美好洛谷
原文
存档评论38 条抓取于