Gadget Hackwrench time limit per test 2 seconds memory limit per test 64 megabytes input standard input output standard output Chip 'n' Dale rescue rangers! But observant viewers know that help is usually required by Chip and Dale themselves. Today y…
How far away ? Time Limit: / MS (Java/Others) Memory Limit: / K (Java/Others) Total Submission(s): Accepted Submission(s): Problem Description There are n houses in the village and some bidirectional roads connecting them. Every day peole always like…
题目传送门 题意:一棵有向的树,问u到v是否可达 分析:假设是无向树,DFS时正向的权值+1,反向的权值-1,然后找到LCA后判断dep数组和d数组就可以了 /************************************************ * Author :Running_Time * Created Time :2015/10/5 星期一 10:28:49 * File Name :G_2.cpp **************************************…
<题目链接> 题目大意:给你一棵带有边权的树,然后进行q次查询,每次查询输出指定两个节点之间的距离. 解题分析:本题有多重解决方法,首先,可用最短路轻易求解.若只用LCA解决本题,也有三种常用的做法,具体方法如下: LCA转RMQ解法: #include <cstdio> #include <cmath> #include <vector> #include <cstring> #include <algorithm> using n…
求LCA(近期公共祖先)的算法有好多,按在线和离线分为在线算法和离线算法. 离线算法有基于搜索的Tarjan算法较优,而在线算法则是基于dp的ST算法较优. 首先说一下ST算法. 这个算法是基于RMQ(区间最大最小值编号)的,不懂的能够这里学习一些 而求LCA就是把树通过深搜得到一个序列,然后转化为求区间的最小编号. 比方说给出这样一棵树. watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveTk5MDA0MTc2OQ==/font/5a6L5L2T/fo…
Closest Common Ancestors Time Limit: 2000MS   Memory Limit: 10000K Total Submissions: 13370   Accepted: 4338 Description Write a program that takes as input a rooted tree and a list of pairs of vertices. For each pair (u,v) the program determines the…
ST算法是求最近公共祖先的一种 在线 算法,基于RMQ算法,本代码用双链树存树 预处理的时间复杂度是 O(nlog2n)   查询时间是 O(1) 的 另附上离线算法 Tarjan 的链接: http://www.cnblogs.com/hadilo/p/5840390.html 首先预处理出深度,以及 DFS 序,这里的DFS序是指回溯时也算上,比如 void dfs(int x,int dep) { int i; d[x]=dep; a[++top]=x; ;i=next[i]) { dfs…
题目大概说一棵边有方向的树,q个询问,每次询问结点u是否能走到v. 倍增LCA搞即可: 除了par[k][u]表示u结点往上走2k步到达的结点, 再加上upp[k][u]表示u结点往上走2k步经过边的状态:-1表示边都是向下,1表示都是向上,0混合. 这样u.v都往LCA上走就能知道u是否能走到v了. #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define M…
LCA(最近公共祖先)的求法有多种,这里先介绍第一种:在线算法. 声明一下:下面的内容参考了http://www.cnblogs.com/scau20110726/archive/2013/05/26/3100812.html. 在线算法就是利用了DFS和RMQ两种算法,它先是预处理好所有情况,然后根据输入输出答案,在输入比较多的时候用比较好. 上面两张图介绍了在线算法的做法,要理解并不难,下面附上实现代码: /******************************* dfs实现代码 **…
Nearest Common Ancestors 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.…