题目链接 Connections between cities LCA的模板题啦. #include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i(0); i < (n); ++i) #define rep(i,a,b) for(int i(a); i <= (b); ++i) #define dec(i,a,b) for(int i(a); i >= (b); --i) #define for…
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2874 题目大意:给出n个点,m条边,q个询问,每次询问(u,v)的最短距离,若(u,v)不连通即不在同一颗树上则输出“Not connected”. 解题思路:这题也是模板题,有所不同的是这次给出的是森林而不是一棵树,所以vis数组得稍作修改,标记vis数组的是当前树的编号.下面给出Tarjan和倍增法两种解法. Tarjan(离线)写法,被MLE坑了,离线写法必须要用静态邻接表,因为虽然n不大,但…
http://acm.hdu.edu.cn/showproblem.php?pid=2874 题意: 求两个城市之间的距离. 思路: LCA题,注意原图可能不连通. 如果不了解离线算法的话,可以看我之前博客写的解释http://www.cnblogs.com/zyb993963526/p/7295894.html #include<iostream> #include<algorithm> #include<cstring> #include<cstdio>…
[题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=2874 [题目大意] 有n个村庄,m条路,不存在环,有q个询问,问两个村庄是否可达, 如果可达则输出最短路. [题解] 因为不存在环,所以是森林,我们计算每个连通块的dfs序,计算块内每个点到根距离 当两个点在同一个连通块时,我们输出其dis值之和减去其LCA的dis值, 否则输出不想连. [代码] #include <cstdio> #include <algorithm> #in…
Connections between cities Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 11964    Accepted Submission(s): 2786 Problem Description After World War X, a lot of cities have been seriously damag…
dfs找出所有节点所在树及到树根的距离及深度及父亲. i和j在一棵树上,则最短路为dis[i]+dis[j]-dis[LCA(i,j)]*2. #include <cstring> #include <cstdio> #define N 10005 #define add(u,v,w) e[++cnt]=(edge){v,head[u],w};head[u]=cnt using namespace std; struct edge{ int to,next,w; }e[N<&…
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2874 题目: Problem Description After World War X, a lot of cities have been seriously damaged, and we need to rebuild those cities. However, some materials needed can only be produced in certain places. So…
Connections between cities Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 4425    Accepted Submission(s): 1263 Problem Description After World War X, a lot of cities have been seriously damag…
Connections between cities [题目链接]Connections between cities [题目类型]LCA Tarjan &题意: 输入一个森林,总节点不超过N(N<10000),由C次询问(C<1000000),每次询问两个点,如果来联通输出,两点之间的距离,如果不来联通,输出"Not connected" &题解: md,就没人吐槽这题询问时有相等的情况吗?我被这个坑了一天= = 最后把ans数组置为-1才过的,以前一直初…
Connections between cities Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Problem Description After World War X, a lot of cities have been seriously damaged, and we need to rebuild those cities. However, some mat…