POJ 1986 Distance Queries (LCA)

题目链接:POJ 1986 Distance Queries (LCA)

题意分析:
求树上两点间的最短距离。

解题思路:
典型的离线LCA啊,主要是涉及到上一题的条件输入。不过本题边的朝向并不影响解题:)

个人感受:
时间主要废在看这题和上题题目上了2333

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#define ll long long
#define pr(x) cout << #x << " = " << (x) << '\n';
using namespace std;
const int INF = 0x7f7f7f7f;
const int MAXN = 4e4 + 111;
const int MAXM = 8e4 + 222;
struct Edge {
int to, w, next;
}edge[MAXM];
int head[MAXN], tol;
struct Query {
int to, id, next;
}query[MAXM];
int qhead[MAXN], qtol, ans[MAXN], dis[MAXN];
bool vis[MAXN];
int par[MAXN];
int find(int x) {
return par[x] == x ? x : par[x] = find(par[x]);
}
void init() {
tol = qtol = 0;
memset(head, -1, sizeof head);
memset(qhead, -1, sizeof qhead);
}
void addedge(int u, int v, int w) {
edge[tol].to = v;
edge[tol].w = w;
edge[tol].next = head[u];
head[u] = tol++;
}
void qaddedge(int u, int v, int id) {
query[qtol].to = v;
query[qtol].id = id;
query[qtol].next = qhead[u];
qhead[u] = qtol++;
}
void dfs(int u, int sum) {
dis[u] = sum;
vis[u] = 1;
for (int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to;
if (!vis[v]) {
dfs(v, sum + edge[i].w);
}
}
}
void tarjan(int u) {
par[u] = u;
vis[u] = 1;
for (int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].to;
if (vis[v]) continue;
tarjan(v);
par[v] = u;
}
for (int i = qhead[u]; ~i; i = query[i].next) {
int v = query[i].to;
if (vis[v]) {
ans[query[i].id] = dis[u] + dis[v] - 2 * dis[find(par[v])];
}
}
}
int main()
{
#ifdef LOCAL
freopen("C:\\Users\\apple\\Desktop\\in.txt", "r", stdin);
#endif
int n, m;
while (~scanf("%d%d", &n, &m)) {
int u, v, w, k;
init();
char s[2];
for (int i = 0; i < m; ++i) {
scanf("%d%d%d%s", &u, &v, &w, s);
addedge(u, v, w);
addedge(v, u, w);
}
scanf("%d", &k);
for (int i = 0; i < k; ++i) {
scanf("%d%d", &u, &v);
qaddedge(u, v, i);
qaddedge(v, u, i);
}
memset(vis, 0, sizeof vis);
dfs(1, 0);
memset(vis, 0, sizeof vis);
tarjan(1);
for (int i = 0; i < k; ++i) {
printf("%d\n", ans[i]);
}
}
return 0;
}


广告时间

Java学习网站: how2j

VPS: VPS

梦想世界上每个人都能给我一元钱,2333