RMQ求LCA

RMQ和LCA详解 关于RMQ和LCA的关系的知识,如何用RMQ和LCA的转换 立即下载

落谷模板

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#define MAXN 1010001
using namespace std;
int n,m,to[MAXN],nxt[MAXN],s,head[MAXN],e,pos[MAXN],dfn[MAXN],u,v,dep[MAXN],lg[MAXN];
int st[MAXN][20];
inline void add( int x,int y)
{
    e++;
    to[e]=y;
    nxt[e]=head[x];
    head[x]=e;
}
void dfs(int x,int f)
{
    dfn[++e]=x;
    pos[x]=e;
    for(int i=head[x];i;i=nxt[i])
    {
        int y=to[i];
        if(y!=f)
        {
            dep[y]=dep[x]+1;
            dfs(y,x);
            dfn[++e]=x;
        }
    }


}
int lca(int x,int y)
{
    int pc,pcc,l;
    if(pos[x]>pos[y]) swap(x,y);
    pc=pos[x];
    pcc=pos[y];
    l=lg[pcc-pc+1];
    if(dep[st[pc][l]]<dep[st[pcc-(1<<l)+1][l]])
        return st[pc][l];
        else
        return st[pcc-(1<<l)+1][l];
}
int main()
{
//  freopen("1.txt","r",stdin);
    cin>>n>>m>>s;
    memset(dep,0x7f,sizeof(dep));
    for(int i=1;i<n;i++)
    {
        scanf("%d%d",&u,&v);
        add(u,v);
        add(v,u);
    }
    e=0;
    dep[s]=0;
    dfs(s,0);
    lg[0]=-1;
    for(int i=1;i<=e;i++)
    {
        st[i][0]=dfn[i];
    }
    //i<=n就行了
    for(int i=1;i<=e;i++)
    {
        if((i&(i-1))==0) lg[i]=lg[i-1]+1;
        else lg[i]=lg[i-1];
    }
    for(int i=1;i<=lg[e];i++)   //j+(1<<i)-1<=e就行了
    {
        for(int j=1;j+(1<<i)-1<=e;j++)
        {
            //右边的dep[st[j+(1<<(i-1)][i-1]]!!!
            //                ↑
            //下面else里也是
            if(dep[st[j][i-1]]<dep[st[j+(1<<(i-1))][i-1]])
            st[j][i]=st[j][i-1];
            else st[j][i]=st[j+(1<<(i-1))][i-1];
        }   
    }
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d",&u,&v);
        printf("%d\n",lca(u,v));
    }
}
手把手教你用Deep Single-Image Portrait Relighting实现人像光影重塑(附GitHub代码) 本文提供了一份详细的实战指南,手把手教你利用Deep Single-Image Portrait Relighting技术实现人像光影重塑。文章从环境搭建、核心原理拆解出发,逐步指导构建简易重光照流程,并探讨了使用预训练模型进行效果优化的进阶方法,最后附上避坑指南与常见问题排查,帮助开发者快速上手这一AI图像处理技术。 阅读详情

相关推荐

思科模拟器CIsco Packet Tracer利用三层交换机实现VLAN间路由

版权声明:如果对大家有帮助,大家可以自行转载的。 1.技术原理: 三层交换机具备网络层的功能,实现 VLAN 相互访问的原理是:利用三层交换机的路由功能,通过识别数据包的 IP 地址,查找路由表进行选路转发,三层交换机利用直连路由可以实现不同 VLAN 之间的相互访问。三层交换机给接口配置 IP 地址。采用 SVI(交换虚拟接口)的方式实现 VLAN 间互连。SVI 是指为交换机中的VLAN 创建...

qq_37992321的博客 1万+

求LCA的四种方法(暴力,倍增,RMQ+ST,Tarjan)

P3379 【模板】最近公共祖先(LCA) #include<bits/stdc++.h> using namespace std; struct Edge { int to,next; }edge[500005*2];//无向图,两倍开 int head[500005],grand[500005][21],depth[500005],lg[500001]; int cnt,n,m,s; inline int read() { int x=0,f=1;char ch=getch.

春弦的博客 6968

用Python的fengwo模块复刻通达信筹码峰(COST/WINNER),选股效率提升10倍

本文介绍了如何使用Python的fengwo模块高效复刻通达信的筹码峰(COST/WINNER)计算,显著提升选股效率。通过C++内核与多线程优化,fengwo模块将传统Python实现的数小时计算压缩至分钟级,解决了量化交易中的性能瓶颈问题。文章详细解析了筹码峰计算原理、fengwo模块的技术架构及实战应用,助力量化开发者构建高效选股系统。

weixin_29062823的博客 438

倍增 || ST-RMQ 求LCA

视频讲解戳这里(bj聚聚讲的非常好,一听就懂) 由luogu一道模板题讲起传送门(都9102年,这题还卡输入输出,要吸氧才能过) LCA:求两个点的最近公共祖先 倍增求LCA: 有很多博客图文并茂讲的非常清楚,倍增LCA的主要思想就是,先将u,v(保证u的深度更深)两点调整到同一水平线 情况一:u==v,那就说明最近公共祖先是u,这种情况说明u,v在同一边,祖先自然是深度较浅的那一个...

一只不争气的蒸汽机的博客 345

论文翻译:2024 High-Confidence Computing A survey on large language model (LLM) security and privacy: The

大型语言模型(LLMs),如ChatGPT和Bard,已经彻底改变了自然语言理解和生成。它们具有深度语言理解能力、类似人类的文本生成能力、上下文意识和强大的问题解决技能,使它们在各个领域(例如搜索引擎、客户支持、翻译)中变得不可或缺。同时,LLMs也在安全领域获得了关注,揭示了安全漏洞并展示了它们在安全相关任务中的潜力。本文探讨了LLMs与安全性和隐私的交集。具体来说,我们研究了LLMs如何积极影响安全性和隐私,与它们使用相关的潜在风险和威胁,以及LLMs内部的固有漏洞。

CSPhD-winston的博客 1722

【25届数字IC秋招总结】面试经验6——经纬恒润

25届数字ic面试记录——经纬恒润

lalala0635的博客 991

LCA(最近公共祖先)+RMQ(区间最值)详解

LCA(最近公共祖先) 首先区别祖先和父亲节点:比如4的父亲节点是2,祖先节点是2,1 。5的父亲节点是2,祖先节点是2,1 求解最近公共祖先,比如要求解4和3的最近公共祖先就是1。4和5的最近公共祖先就是2 求解最近公共祖先的方法有很多,比如最简单暴力的方法就是一个一个向上找 还有就是倍增优化,用欧拉序加上ST表。 暴力求解LCA #include<bits/stdc++.h&...

ReverieZH的博客 1255

【量化入门】Tushare库获取公募基金的历史净值

在本文中,我们将介绍如何使用Python的Tushare库获取公募基金的历史净值。

木头大左的博客 1142

RMQ求LCA【ST】算法

RMQ求LCA其实非常简单的啦 我们需要理解两个基本的工具: 1.欧拉序列; 2.线段树,二叉搜索树或者其它基本区间寻求最值的方法; 所以说LCA和区间有什么关系? 举个栗子: 我们将欧拉序列E打出: 【1,2,4,2,5,2,1,3,6,3,1】(先自己想想怎么实现) 在打印序列的同时记录下每个节点第一次出现的位置R 【1,2,8,3,5,9】 另外别忘了给欧拉序列标深度...

Wyt_code的博客 1093

ZYNQ 使用AXI_BRAM实现PS与PL 数据交互数据交互

有时CPU需要与PL进行小批量的数据交换,可以通过Block RAM实现。通过Zynq 的GP Master 接口读写PL端的 BRAM,实现PS与PL的交互。加入自定义的 FPGA 程序,并利用 AXI4 总线进行配置,通知何时读写 BRAM。CPU通过 AXI BRAM Controller 读取 BRAM 数据,CPU 仅配置自定义的 PL BRAM Controller 的寄存器,不通过它读写数将BRAM与socket进行联合使用,将电脑的数据发到PS端,PS端放在PL端,PL端再发给PS端,P据。

wangjie36的博客 1万+

一文搞懂蚁群算法Ant Colony Optimization(ACO)!!!(灵感起源+数学原理+代码实现+实战应用)

本文系统介绍了蚁群算法的原理与实现。首先从蚂蚁觅食行为出发,阐释了信息素正反馈机制如何引导群体找到最短路径。随后详细解析了算法的数学模型,包括状态转移规则和信息素更新机制。通过MATLAB代码演示了算法在旅行商问题(TSP)中的应用,展示了路径构建和优化的完整流程。最后讨论了算法的优势、局限性和实际应用场景。蚁群算法通过模拟生物智能,为解决复杂优化问题提供了一种高效方法,其核心在于信息素的正反馈机制与随机探索的平衡。

qq_42212808的博客 887

[算法学习]——通过RMQ与dfs序实现O(1)求LCA(含封装板子)

每周五篇博客:(3/5)

Resot的博客 1459

人形机器人新产品导入(NPI)工艺工程师的角色与技术解析

本文系统解析人形机器人NPI工程师的核心职责与能力要求。主要内容包括:1)NPI工程师需主导装配工艺设计、样品试做及问题闭环,涉及公差分析(如尺寸链计算)、工艺评审与FMEA应用;2)要求输出完整工艺文档体系,并跟踪试产至量产全过程;3)任职资格强调3年以上机器人/智能制造行业经验,掌握SPC、公差计算等质量工具,熟悉点胶/焊接等工艺及特殊材料特性;4)通过实际案例展示关节精度优化、新物料验证等典型工作场景;5)提供基于职责的面试问题及技术性解答方案。文章聚焦技术细节,为从业者提供实用参考框架。

郑伟强dev的专栏 381

洛谷 - P3379 【模板】最近公共祖先(LCA)(RMQ求LCA/Tarjan求LCA)

题目链接:点击查看 题目大意:给出一棵 n 个点组成的有根树,再给出 m 次询问,每次询问需要回答点 x 和点 y 的 lca 题目分析:今天新学了两种蛮有意思的求 LCA 的方法,总结一下四种方法各有利弊吧,实现复杂度参考我自己,如果有代码大佬能闭着眼随便写的话,忽略即可 Orz 树上倍增求LCA: 时间复杂度: 预处理:O( nlogn ) 查询:O( logn ) 空间复杂度:O( nlogn ) 实现复杂度:最简单 树链剖分求LCA: 时间复杂度: 预处理:O( n )

Falcon的博客 566

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

dfs序+RMQ求LCA详解

首先安利自己倍增求LCA的博客,前置(算不上)知识在此。 LCA有3种求法:倍增求lca(上面qwq),树链剖分求lca(什么时候会了树链剖分再说。),还有,标题。 是的你也来和我一起学习这个了qwq。 开始吧。 众所周知,每当你dfs时,你都能产生一棵dfs树,可以根据你的dfs序来构建。 such as(丑陋的画风): 一个dfs的顺序。 以这个为例:...

weixin_30916125的博客 872

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

利用RMQ -ST求 LCA

描述上上回说到,小Hi和小Ho使用了Tarjan算法来优化了他们的“最近公共祖先”网站,但是很快这样一个离线算法就出现了问题:如果只有一个人提出了询问,那么小Hi和小Ho很难决定到底是针对这个询问就直接进行计算还是等待一定数量的询问一起计算。毕竟无论是一个询问还是很多个询问,使用离线算法都是只需要做一次深度优先搜索就可以了的。那么问题就来了,如果每次计算都只针对一个询问进行的话,那么这样的算法事实...

a1046765624的博客 549

深度学习工具包 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")

RMQ在线求LCA

#include<bits/stdc++.h>using namespace std;#define begin Begin #define next Next #define rank Rank#define REP(i, a, b) for (int i = (a), _end_ = (b); i <= _end_; ++i) #define ER(i, a) for (int i = begi

Free Loop~~~跳动的恒星 778

RMQ求LCA(自用记录)

//因为我st表中记录的是欧拉序的下标,所以deep[]应该是记录欧拉序下标的deep //RMQ 是对欧拉序 进行处理!!! //为什么st表中存下标,而不是deep, //因为我们求的是节点,而不是deep的值,如果知道最小的deep而求lca的话 //在一个树中,一个深度会由很多的点构成,所以知道deep是无法求出所对应的节点的 //而知道在ol中的下标,则可唯一确定一个顶点,与之对应,及LCA. # include<bits/stdc++.h> # define rep(i,be,en)

rickwang000的博客 295

ST(RMQ)算法(在线)求LCA

在此之前,我写过另一篇博客,是倍增(在线)求LCA。有兴趣的同学可以去看一看。概念以及各种暴力就不在这里说了,那篇博客已经有介绍了。 不会ST算法的同学点这里ST(RMQ)算法在线求LCA这个算法的思想,就是将LCA问题转化成RMQ问题。怎么将LCA转成RMQ?我们首先用dfsO(N)遍历一遍。比如下图: 得到一个dfs序(从儿子回到父亲也要算一遍): 1->2->4->7->4->8->

A1847225889的博客 1107

RMQ求LCA模板:

//#pragma comment(linker,"/STACK:327680000,327680000") #include <iostream> #include <cstdio> #include <cmath> #include <vector> #include <cstring> #include <al...

weixin_30763455的博客 79

BZOJ1906树上的蚂蚁&BZOJ3700发展城市——RMQ求LCA+树链的交

题目描述 众所周知,Hzwer学长是一名高富帅,他打算投入巨资发展一些小城市。Hzwer打算在城市中开N个宾馆,由于Hzwer非常壕,所以宾馆必须建在空中,但是这样就必须建立宾馆之间的连接通道。机智的Hzwer在宾馆中修建了N-1条隧道,也就是说,宾馆和隧道形成了一个树形结构。Hzwer有时候会花一天时间去视察某个城市,当来到一个城市之后,Hzwer会分析这些宾馆的顾客情况。对于每个顾...

weixin_33895475的博客 215
上一篇: SPFA模板
下一篇: spfa+位运算 2017.10.9 t3
pcccc0616
博客等级 码龄10年 13粉丝 25原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值