POJ 1330(LCA/倍增法模板)】的更多相关文章

链接:http://poj.org/problem?id=1330 题意:q次询问求两个点u,v的LCA 思路:LCA模板题,首先找一下树的根,然后dfs预处理求LCA(u,v) AC代码: #include<iostream> #include<algorithm> #include<cmath> #include<cstring> #include<set> #include<string> #include<vector&…
/* 先来个倍增 */ #include<iostream> #include<cstring> #include<cstdio> #define maxn 10010 using namespace std; ],dep[maxn],out[maxn],root; struct node { int u,v,t,pre; }e[maxn*]; void Add(int from,int to) { num++; e[num].u=from; e[num].v=to;…
1.输入树中的节点数N,输入树中的N-1条边.最后输入2个点,输出它们的最近公共祖先. 2.裸的最近公共祖先. 3. dfs+ST在线算法: /* LCA(POJ 1330) 在线算法 DFS+ST */ #include<iostream> #include<stdio.h> #include<string.h> using namespace std; ; *MAXN];//rmq数组,就是欧拉序列对应的深度序列 struct ST{ *MAXN]; *MAXN][…
一.前人种树 博客:最近公共祖先 LCA 倍增法 博客:浅谈倍增法求LCA 二.沙场练兵 题目:POJ 1330 Nearest Common Ancestors 代码: const int MAXN = 10010; const int DEG = 20; struct Edge { int to,next; }edge[MAXN*2]; int head[MAXN],tot; void addedge(int u,int v) { edge[tot].to = v; edge[tot].ne…
倍增法模板题 #include<iostream> #include<cstring> #include<cstdio> #include<queue> using namespace std; #define maxn 1000 #define DEG 20 struct Edge{ int to,next; }edge[maxn*maxn*]; int head[maxn],tot; void addedge(int u,int v){ edge[tot…
题目大意:给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先. 整体步骤:1.使两个点深度相同:2.使两个点相同. 这两个步骤都可用倍增法进行优化.定义每个节点的Elder[i]为该节点的2^k(或者说是二进制中的1,10,100,1000...)辈祖先.求它时要利用性质:cur->Elder[i]==cur->Elder[i-1]->Elder[i-1].具体步骤看代码. #include <cstdio> #include <cstring> #inclu…
今天学LCA,先照一个模板学习代码,给一个离线算法,主要方法是并查集加上递归思想. 再搞,第一个离线算法是比较常用了,基本离线都用这种方法了,复杂度O(n+q).通过递归思想和并查集来寻找最近公共祖先,自己模拟下过程就可以理解了. 然后就是在线算法,在线算法方法就很多了,比较常用的是LCA的RMQ转换,然后还有线段树,DP等,最后效率最高的就是倍增法了每次查询O(LogN) 这道题是离线的. 给出离线的Tarjan和倍增算法吧. 代码: #include<iostream> #include&…
倍增法加了边的权值,bfs的时候顺便把每个点深度求出来即可 #include<iostream> #include<cstring> #include<cstdio> #include<queue> using namespace std; #define maxn 40005 #define DEG 20 struct Edge{ int to,next,w; }edge[maxn*]; int head[maxn],tot; void addedge(i…
[简介] 解决LCA问题的倍增法是一种基于倍增思想的在线算法. [原理] 原理和同样是使用倍增思想的RMQ-ST 算法类似,比较简单,想清楚后很容易实现. 对于每个节点u , ancestors[u][k] 表示 u 的第2k个祖先是谁.很容易就想到递推式: ancestors[j][i] = ancestors[ancestors[j][i - 1]][i - 1];  根据二进制原理,理论上 u 的所有祖先都可以根据ancestors数组多次跳转得到,这样就间接地记录了每个节点的祖先信息. …
POJ 1330 Description A rooted tree is a well-known data structure in computer science and engineering. An example is shown below: In the figure, each node is labeled with an integer from {1, 2,...,16}. Node 8 is the root of the tree. Node x is an anc…