http://poj.org/problem? id=1330 给一个有根树,一个查询节点(u,v)的近期公共祖先 836K 16MS #include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<vector> #include<string> #include<set> #include<map> con…
用的离线算法Tarjan 该算法的详细解释请戳 http://www.cnblogs.com/Findxiaoxun/p/3428516.html 做这个题的时候,直接把1470的代码copy过来,改了改输入输出.这个的难度比那个低. #include<cstdio> #include<algorithm> #include<cstring> #include<vector> using namespace std; ; int father[MAXN],a…
有关概念: 最近公共祖先(LCA,Lowest Common Ancestors):对于有根树T的两个结点u.v,最近公共祖先表示u和v的深度最大的共同祖先. Tarjan是求LCA的离线算法(先存储所有询问,再进行运算) 思路: 从根结点开始DFS,对遍历到的结点u标记已访问,创建新集合,元素为u,再遍历u的每一个儿子,回溯时将每个儿子的集合并到u的集合上,用并查集记录集合中的每个元素的fa为u,接着处理询问,对于关于u的每一个询问,若另一个结点v已访问,则可断定LCA(u,v)为fav,记录…
Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 18136   Accepted: 9608 Description A rooted tree is a well-known data structure in computer science and engineering. An example is shown below: In the figure, each…
Closest Common Ancestors Time Limit: 2000MS   Memory Limit: 10000K Total Submissions: 13372   Accepted: 4340 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…
A - Nearest Common Ancestors Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%lld & %llu Submit Status Description A rooted tree is a well-known data structure in computer science and engineering. An example is shown below: In the figu…
题意要求一棵树上,两个点的最近公共祖先 即LCA 现学了一下LCA-Tarjan算法,还挺好理解的,这是个离线的算法,先把询问存贮起来,在一遍dfs过程中,找到了对应的询问点,即可输出 原理用了并查集和dfs染色,先dfs到底层开始往上回溯,边并查集合并 一边染色,这样只要询问的两个点均被染色了,就可以输出当前并查集的最高父亲一定是LCA,因为我是从底层层层往上DSU和染色的,要么没被染色,被染色之后,肯定就是当前节点是最近的 #include <iostream> #include <…
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 ancestor of node y if n…
该算法的详细解释请戳: http://www.cnblogs.com/Findxiaoxun/p/3428516.html #include<cstdio> #include<algorithm> #include<cstring> #include<vector> using namespace std; ; int father[MAXN],ancestor[MAXN]; bool visit[MAXN]; int ans[MAXN]; vector&l…
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2586 这题以前做过…现在用tarjan搞一发…竟然比以前暴力过的慢………… 由于是离线算法,需要Query来保存查询数据,Ans来保存结果.最后输出的时候按照idx的顺序输出,所以胡搞了个排序.. dfs每次更新depth,当前点depth是上一个点累积下来的. /* ━━━━━┒ギリギリ♂ eye! ┓┏┓┏┓┃キリキリ♂ mind! ┛┗┛┗┛┃\○/ ┓┏┓┏┓┃ / ┛┗┛┗┛┃ノ) ┓┏┓…