HDU2874【LCA(模板)】】的更多相关文章

/*********--LCA模板--***************/ //设置好静态参数并构建好图的邻接表,然后调用lca_setquery()设置查询 //最后调用lca_start(),在lca::dfs中的your code处理每次查询 //复杂度O(M+Q) //表示图的邻接表 #define N 40100 #define MAX_Q 200 struct node { int to,next,w; }edge[*N]; int pre[N],cnt; int ans[MAX_Q];…
倍增求lca模板 https://www.luogu.org/problem/show?pid=3379 #include<cstdio> #include<iostream> #include<cmath> #include<cstring> using namespace std; int t,n,cnt,m; int x,y; ][],p,root; ]; ]; ]; ; struct node { int next,to; }e[*]; inline…
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2874 题意: 给出 n 个顶点 m 条边的一个森林, 有 k 个形如 x y 的询问, 输出 x, y 之间的最短路径. 思路: 如果将森林换成一棵树的话就是一道 lca 模板题了, 不过本题需要稍作改动. 解法1: tarjan 只需要先判断一下 x, y 是否在一颗树里面就 ok 了, 不过这道题的询问有点多, 很容易 mle. 代码: #include <iostream> #includ…
How far away ? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 9359    Accepted Submission(s): 3285 Problem Description There are n houses in the village and some bidirectional roads connecting…
题目: 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 ancesto…
How far away ? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 25408    Accepted Submission(s): 10111 Problem Description There are n houses in the village and some bidirectional roads connectin…
题目链接:https://www.luogu.org/problemnew/show/P3379 题意:LCA模板题. 思路:今天开始学树剖,先拿lca练练.树剖解lca,两次dfs复杂度均为O(n),每次查询为logn,因此总复杂度为:O(2*n+m*logn). 代码: #include<cstdio> #include<cstring> using namespace std; ; struct node{ int v,next; }edge[*maxn]; int n,m,…
第一题LCA,代码参考自:Ice_Crazy 思路: 这个最短路算法是想都别想了,可以看出这幅图就是树嘛,那么对于查询就是求树上两个结点最短距离. 这里就是利用LCA的tarjan离线算法. 算法的大致流程: 对于每一点u, ①  :建立以u为代表元素的集合. ②  :遍历与u相连的结点v,如果没有访问过,对与v使用Tarjan-LCA算法,结束后,将v的集合并入u的集合. ③  :对于与u相关的询问(u,v),如果v被访问过,则结果就是v所在集合的代表. 在这里还需要算距离,需要深度:dis<…
给定一棵树求任意两个节点的公共祖先 tarjan离线求LCA思想是,先把所有的查询保存起来,然后dfs一遍树的时候在判断.如果当前节点是要求的两个节点当中的一个,那么再判断另外一个是否已经访问过,如果访问过的话,那么它的最近公共祖先就是当前节点祖先. 下面是tarjan离线模板: #include <cstdio> #include <cstring> #include <algorithm> using namespace std; ; struct Edge { i…
题目链接:传送门 题意: 给定一棵树,求两个点之间的距离. 分析: LCA 的模板题目 ans = dis[u]+dis[v] - 2*dis[lca(u,v)]; 在线算法:详细解说 传送门 代码例如以下: #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 40010; str…