最近公共祖先 模板 裸题

最近公共祖先三种算法详解 + 模板题 建议新手收藏 例题: 信息学奥赛一本通 祖孙询问 距离 阅读详情

最近公共祖先

Time Limit:10000MS  Memory Limit:65536K
Total Submit:75 Accepted:67 
Case Time Limit:1000MS

Description

给出一棵有N(编号1到N)个节点的有根树,求出指定节点对的最近公共祖先! 
 
对于树中节点x而言,从根节点到达x的这一条路径中经过的所有节点,都称为x的祖先。 
如上图所表示的树中, 根节点为8。8、4、10、16都是12的祖先。对于6和12这对节点而言,从6出发往上朝根走和从12出发往上朝根走的两条路径最早交汇的地点是4号节点,因此4号点是6和12的最近公共祖先。 
同理,11和9的最近公共祖先是8; 10和3的最近公共祖先是10;2和7的最近公共祖先是4......

Input

第一行,一个整数N。表示树中节点总数 
接下来N-1行,每行两个整数x和y,表示x是y的父亲。 
接下来一行,一个整数M,表示询问的总数 
接下来M行,每行两个整数a和b,表示询问a和b的最近公共祖先。

Output

M行,每行一个整数,表示对应询问的答案。

Sample Input

输入样例1:
16 
1 14
8 5
10 16
5 9
4 6
8 4
4 10
1 13
6 15
10 11
6 7
10 2
16 3
8 1
16 12
3
16 7
14 9
3 10
输入样例2:

5
2 3
3 4
3 1
1 5
2
3 5
4 5

Sample Output

输出样例1:
4
8
10
输出样例2:
3
3

Hint

2<=N<=10000 
1<=M<=10000

Source

改编自POJ1330


<pre name="code" class="cpp">#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
#define maxn 10009
#define maxm 10009
int dep[maxn], fa[maxn][20], /*BigS 这个变量废弃了*/;
vector <int> edge[maxn];
void fdepfa(int cur)		//计算各点的深度和祖先 
{
	int i, k;
	dep[cur]=dep[fa[cur][0]]+1;	//当前点的深度=父亲节点的深度+1 
	k=ceil(log(dep[cur])/log(2));	//最多网上跳 k 次 
	for(i=1; i<=k; i++)
	{
		fa[cur][i]=fa[fa[cur][i-1]][i-1];
	}
	vector<int>::iterator it;	//深搜儿子节点 
	for(it=edge[cur].begin(); it!=edge[cur].end(); it++)
	{
		fdepfa(*it);
	}
}
int lca(int x, int y)
{
	int i, k, s;
	if(dep[x]<dep[y])	swap(x, y);	//保证x节点始终在y节点之下,即保证x的深度小于y的深度 
	k=dep[x]-dep[y];		//把x跳到和y同一深度需要向上走 k 层 
	//for(i=0; i<=BigS; i++)
	s=ceil(log(dep[x])/log(2));//有这么一天,我把上面那句话改了 
	for(i=0; i<=s; i++)
	{
		if(k&(1<<i))x=fa[x][i];	//要走k步,按位走k步 
	}
	if(x==y)	return x;	//如果x的编号等于y的编号,运气太好,y就是x的祖先 
	s=ceil(log(dep[x])/log(2));	//可惜x和y没有直接祖孙关系,只有共同的祖先,最多往上跳s次 
	for(i=s; i>=0; i--)
		if(fa[x][i]!=fa[y][i])	//从深度小的祖先对照,找到第一个不相同的,直接跳上去 
		{
			x=fa[x][i];
			y=fa[y][i];
		}
	return fa[x][0];
}
int main()
{
	int i;
	int n, m, x, y, a, b;
	scanf("%d", &n);
	//BigS=log(n)/log(2);	//最大倍增深度 ,没什么用 
	for(i=1; i<n; i++)	//只有n-1条边 
	{
		scanf("%d%d", &x, &y);
		fa[y][0]=x;		//y的父亲为x 
		edge[x].push_back(y);	//vector存边 
	}
	for(i=1; i<=n; i++)	if(fa[i][0]==0){fdepfa(i); break;}//从根节点开始计算各点深度,各点的祖先 
	scanf("%d", &m);
	for(i=1; i<=m; i++)
	{
		scanf("%d%d", &a, &b);
		printf("%d\n", lca(a, b));	//lca(a, b)计算a, b的最近公共祖先的编号 
	}
	return 0;
}



<pre name="code" class="cpp">#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
#define maxn 10009
#define maxm 10009
int dep[maxn], fa[maxn][20];
vector <int> edge[maxn];
void fdepfa(int cur)
{
	int i, k;
	dep[cur]=dep[fa[cur][0]]+1;
	k=ceil(log(dep[cur])/log(2));
	for(i=1; i<=k; i++)	fa[cur][i]=fa[fa[cur][i-1]][i-1];
	vector<int>::iterator it;
	for(it=edge[cur].begin(); it!=edge[cur].end(); it++)
	{
		fdepfa(*it);
	}
}
int lca(int x, int y)
{
	int i, k, s;
	if(dep[x]<dep[y])	swap(x, y);
	k=dep[x]-dep[y];
	s=ceil(log(dep[x])/log(2));
	for(i=0; i<=s; i++)
		if(k&(1<<i))x=fa[x][i];
	if(x==y)	return x;
	s=ceil(log(dep[x])/log(2));
	for(i=s; i>=0; i--)
		if(fa[x][i]!=fa[y][i])
		{
			x=fa[x][i];
			y=fa[y][i];
		}
	return fa[x][0];
}
int main()
{
	int i;
	int n, m, x, y, a, b;
	scanf("%d", &n);
	for(i=1; i<n; i++)
	{
		scanf("%d%d", &x, &y);
		fa[y][0]=x;
		edge[x].push_back(y);
	}
	for(i=1; i<=n; i++)	if(fa[i][0]==0){fdepfa(i); break;}
	scanf("%d", &m);
	for(i=1; i<=m; i++)
	{
		scanf("%d%d", &a, &b);
		printf("%d\n", lca(a, b));
	}
	return 0;
}




避开这些坑!晶圆封装中Wire Bonding(引线键合)的5种常见不良与实战调试心得 本文深入探讨晶圆封装中Wire Bonding(引线键合)的5种常见不良现象,包括Wire Offset、BSOB不良、球径/球厚异常、弧度不良和IMC问题。通过实际案例和参数优化方案,帮助工程师提升封装质量和可靠性,特别适用于半导体封装领域的专业人士。 阅读详情

相关推荐

ComfyUI安装包运行前准备:安装Git

Git 是一个分布式版本控制系统(Version Control System, VCS),用于跟踪和管理文件(尤其是代码)的变更历史。 简单理解就是,git是用来管理文件的版本的,如果有新的版本,就可以使用git来更新。

聚梦小课堂 2万+

【洛谷 P3379】最近公共祖先【LCA模板】

题目描述 题目 如题,给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先。 输入格式 第一行包含三个正整数 N,M,SN,M,SN,M,S,分别表示树的结点个数、询问的个数和树根结点的序号。 接下来 N−1N−1N−1 行每行包含两个正整数 x,yx,yx,y,表示 xxx 结点和 yyy 结点之间有一条直接连接的边(数据保证可以构成树)。 接下来 MMM行每行包含两个正整数 a,ba, ba,b,表示询问 aaa 结点和 bbb 结点的最近公共祖先。 输出格式 输出包含 MMM 行,每行包含一个正整数

绫 1711

别只聊天了!手把手教你为Ollama+Open WebUI搭建本地知识库(基于BGE-M3和Qwen)

本文详细介绍了如何利用Ollama、Open WebUI和BGE-M3构建本地知识库,实现智能问答和文档检索。通过环境准备、文档处理、向量化实战和应用案例,帮助用户突破基础聊天场景,打造高效的个人知识管理体系。特别适合技术文档管理和学术研究场景。

weixin_42523720的博客 478

最近公共祖先

Description 给出一棵有N(编号1到N)个节点的有根树,求出指定节点对的最近公共祖先!    对于树中节点x而言,从根节点到达x的这一条路径中经过的所有节点,都称为x的祖先。  如上图所表示的树中, 根节点为8。8、4、10、16都是12的祖先。对于6和12这对节点而言,从6出发往上朝根走和从12出发往上朝根走的两条路径最早交汇的地点是4号节点,因此4号点是6和12的最近公共祖先

Ciocio 1110

用Python+Charles搞定小程序付费短剧下载(附完整代码与避坑点)

本文详细介绍了如何利用Python和Charles抓包工具实现小程序付费短剧的自动化下载。通过分析小程序视频接口、破解请求参数,并编写Python脚本,读者可以轻松获取并保存短剧内容。文章还提供了完整的代码示例和常见问题的解决方案,特别适合对视频采集和抓包技术感兴趣的开发者。

weixin_28731231的博客 1188

从DC到DCG:手把手教你搭建物理感知综合流程(含DEF文件处理避坑指南)

本文详细介绍了从Design Compiler(DC)过渡到DC Topographical(DCT)和DC Graphical(DCG)的完整操作框架,特别针对DEF文件处理提供避坑方案。通过环境准备、工具升级、DEF文件处理、DCG综合配置等步骤,帮助开发者高效应对28nm以下工艺节点的物理感知综合挑战,显著提升时序收敛效率。

weixin_27966471的博客 380

C++最近公共祖先(LCA版)

C++最近公共祖先(LCA版) 啊呀,这个是我这一个月来听得最懂的一个算法了,真是一个具有纪念意义的时刻。因为我怕我过两天就搞忘了,于是我就只好写这儿了,各位居然大佬爱看不看,(我可真是个秀儿) 大概思路: 用dep[]来标记树的深度,fa[v][k]来标记v点向上2^k 步骤:1.DFS来确定层数,将x,y移到同一水平线; 2.将x,y同时向上移,如果x==y就return x; 不说了,直接看...

CPGhanyue的博客 1360

【赛题解析&命令脚本配置】2023年全国职业院校技能大赛GZ073网络系统管理赛项赛题第10套模块A:网络构建 & (五)网络运维配置+(六)SDN网络配置-命令配置

【赛题解析&命令脚本配置】2023年全国职业院校技能大赛GZ073网络系统管理赛项赛题第10套模块A:网络构建 & (五)网络运维配置+(六)SDN网络配置-命令配置

君逍遥o 809

NKOI 2447 最近公共祖先

最近公共祖先 Time Limit:10000MS  Memory Limit:65536K Total Submit:104 Accepted:91 Case Time Limit:1000MS Description 给出一棵有N(编号1到N)个节点的有根树,求出指定节点对的最近公共祖先! 对于树中节点x而言,从根节点到达x的这一条路径中经过的所有节点,都称为x的祖先。 如上

SuperGate的博客 490

2025年开源气象大模型的实现原理与实践指南

气象大模型在人工智能时代实现了革命性突破,通过深度学习技术以更低的计算成本达到甚至超越传统数值天气预报的精度。开源气象大模型的出现使得全球研究者和机构都能参与气象AI的创新。本文详细解析了开源气象大模型的实现原理,包括核心架构、数据准备、训练方法和实际预测流程,并提供了实践指南。核心架构主要采用Transformer、图神经网络和扩散模型,处理多模态数据融合和时空联合建模。数据体系构建涉及数据来源、预处理和增强策略。模型训练关键技术包括损失函数设计、分布式训练优化和训练过程监控。微调与领域适应策略包括迁移学

专注AI大模型,软件混淆,授权 1181

微信小程序 - 最新详细实现用户保存下载视频到手机相册,将视频临时路径、在线播放地址(网络路径)URL存储到手机,弹出访问手机相册权限询问,支持视频格式mp4、avi、mov、wmv、flv、webm

微信小程序,视频,手机相册,保存,另存为,小程序保存到相册权限,writePhotosAlbum,一键保存视频到手机相册功能(视频来源为链接),第一次要获取用户授权,授权使用相册权限,小程序视频下载,如何把视频下载到相册,下载一个视频到本地相册,显示下载进度,可取消下载,视频下载到本地,微信小程序视频如何下载,保存视频到相机,页面播放视频并下载到本地,安卓系统,苹果ios保存到相册报错,权限拒绝后打不开,添加相册授权弹框拒绝后再也出不来了,实现保存视频到手机相册功能,将mp4在线视频下载并存储到用户的手机中

🏆 前端领域优质创作者 7623

bzoj4568(合并线性基+倍增)

裸题练习模板 #include<iostream> #include<cstring> #include<cmath> #include<cstdio> #include<algorithm> #include<vector> using namespace std; typedef long long ...

weixin_34162695的博客 194

QML教程04 - Image:搞定界面上的所有图片

本文是QML教程系列的第四篇,重点讲解Image控件的实战用法。文章从图片显示常见的变形、卡顿等问题入手,详细介绍了Image的核心属性和使用技巧。主要内容包括:图片路径的三种写法(相对路径、qrc资源、网络URL)、最重要的fillMode属性解析(PreserveAspectFit、PreserveAspectCrop、Stretch的适用场景)、性能优化方法(sourceSize设置)、异步加载(asynchronous)以及圆形头像的实现方案。

BenBierBa的博客 1608

P3379 【模板】最近公共祖先(LCA)

路径压缩的基本思想是,在执行查找操作时,将访问路径上的所有节点直接连接到根节点上。这样做的目的是在下一次查找操作时,能直接访问到根节点,从而减少路径长度,提高查找效率。如题,给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先。,分别表示树的结点个数、询问的个数和树根结点的序号。行,每行包含一个正整数,依次为每一个询问的结果。行每行包含两个正整数。行每行包含两个正整数。的最近公共祖先,故为。的最近公共祖先,故为。的最近公共祖先,故为。的最近公共祖先,故为。的最近公共祖先,故为。结点的最近公共祖先。

cc_even的博客 2078

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

LCA-最近公共祖先

最近公共祖先简称。两个节点的最近公共祖先,就是这两个点的公共祖先里面,离根的那个。为了方便,我们记某点集 的最近公共祖先为LCAU1​U2​...Un​或LCAs。

weixin_42238183的博客 1795

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

最近公共祖先问题

最近公共祖先的倍增法、Tarjan算法等等

m0_62652820的博客 1304

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

最近公共祖先(LCA)(树上倍增)

什么是最近公共祖先呢?其实这是在树上定义的,比如说x节点,那么x节点以及x节点的父节点以及x节点的父节点的父节点的……父节点,这都算是x的祖先,而公共祖先显然是对于两个节点而言的,就是一个节点同时是这两个节点的祖先,那么这个节点就是两个节点的公共祖先,最近公共祖先当然是离他们最近的公共祖先了。画个图来说明一下: ...

AC__dream的博客 1833

最近公共祖先(模板-LCA)

给定一棵有根多叉树,求出指定两个点直接最近的公共祖先。

2301_78700895的博客 968

【模板】最近公共祖先(LCA)

如题,给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先。

DXCcn的博客 834

LCA最近公共祖先求解(四种方法模板)

题目:【模板】最近公共祖先(LCA) 题目链接:【模板】最近公共祖先(LCA) - 洛谷 题面: 树链剖分模板: 思想: 求解LCA的过程就是轻重链的跳转,跟数链剖分求任意两点间的距离一样的操作 #include<bits/stdc++.h> using namespace std; #define endl "\n" #define N 500005 int head[N], to[N << 1], nex[N << 1],...

m0_55682843的博客 2532

【leetcode】236. 二叉树的最近公共祖先

🚅【leetcode】236. 二叉树的最近公共祖先🚀题目💥leetcode代码模板🚀思路💻代码🍪总结 🚀题目 leetcode原题链接 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 示例 1: 输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1

laplacepoisson的博客 944

洛谷 P3379 [模板] 最近公共祖先(LCA)

LCA 倍增算法 邻接表 DFS 动态规划 线性dp 洛谷题解 C++代码 附详细注释

一只摸鱼的bbc 747

LCA 最近公共祖先

参考:https://www.cnblogs.com/JVxie/p/4854719.html 首先是最近公共祖先的概念(什么是最近公共祖先?): Tarjan/DFS+ST/倍增     在一棵没有环的树上,每个节点肯定有其父亲节点和祖先节点,而最近公共祖先,就是两个节点在这棵树上深度最大的公共的祖先节点。     换句话说,就是两个点在这棵树上距离最近的公共祖先节点。     ...

森宝的博客 490

【模板】最近公共祖先(LCA)倍增

对于 100\%100% 的数据,1 \leq N,M\leq 5000001≤N,M≤500000,1 \leq x, y,a ,b \leq N1≤x,y,a,b≤N,接下来 N-1N−1 行每行包含两个正整数 x, yx,y,表示 xx 结点和 yy 结点之间有一条直接连接的边(数据保证可以构成树)。第一行包含三个正整数 N,M,SN,M,S,分别表示树的结点个数、询问的个数和树根结点的序号。故输出依次为 4, 4, 1, 4, 44,4,1,4,4。提交答案加入题单复制题目。

no_play_no_games的博客 1124

最近公共祖先(LCA模板总结)

输入:第1行包含一个整数T,表示测试用例的数量。每个测试用例的第1行都包含整数N(2≤N≤10,000),表示树中的节点数。接下来N-1行,每行都包含一对边的整数,第1个整数是第2个整数的父节点(有N个节点的树有N-1条边)。每个测试用例的最后一行都包含两个不同的整数,求其LCA。给你一棵树,找出两点的最近公共祖先LCA。

2301_80882026的博客 418

最近公共祖先【LCA】 模板

LCA即最近公共祖先,是指 :在有根树中,找出某两个结点u和v最近的公共祖先。 时间复杂度O(nlogn+m+n) 步骤: 1.将树看作一个无向图,从根节点开始深搜,得到一个遍历序列。 2.在x~y区间中利用RMQ算法找到深度最小返回其下标。 可以上洛谷找模板题测试:https://www.luogu.org/problemnew/show/P3379 #include&lt...

几许情愁的博客 213
上一篇: 【NOIP2014 Day1 T2】联合权值
下一篇: 【4连WA】【Usaco Oct08 Gold】奶牛串门(Pasture Walking)
Formiko
博客等级 码龄11年 20粉丝 67原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值