Description
Farmer John’s cows refused to run in his marathon since he chose a path much too long for their leisurely lifestyle. He therefore wants to find a path of a more reasonable length. The input to this problem consists of the same input as in “Navigation Nightmare”,followed by a line containing a single integer K, followed by K “distance queries”. Each distance query is a line of input containing two integers, giving the numbers of two farms between which FJ is interested in computing distance (measured in the length of the roads along the path between the two farms). Please answer FJ’s distance queries as quickly as possible!
Input
-
Lines 1…1+M: Same format as “Navigation Nightmare”
-
Line 2+M: A single integer, K. 1 <= K <= 10,000
-
Lines 3+M…2+M+K: Each line corresponds to a distance query and contains the indices of two farms.
Output -
Lines 1…K: For each distance query, output on a single line an integer giving the appropriate distance.
Sample Input
7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
3
1 6
1 4
2 6
Sample Output
13
3
36
Hint
Farms 2 and 6 are 20+3+13=36 apart.
LIT - AC
将边当作虚点,连接到两个点。
在点上维护以之为根的splay子树上的点权和。
查询两点间路径长,就是把两点间路径split出来,输出splay根上的值。
int n, m, w[MAXN << 1];
int c[MAXN << 1][2], fa[MAXN << 1], dis[MAXN << 1];
bool rev[MAXN << 1];
bool get(int x) {
return x == c[fa[x]][1];
}
bool isroot(int x) {
return x != c[fa[x]][0] && x != c[fa[x]][1];
}
void pushup(int x) {
int lc = c[x][0], rc = c[x][1];
dis[x] = dis[lc] + dis[rc] + w[x];
}
void pushdown(int x) {
int lc = c[x][0], rc = c[x][1];
if (rev[x]) {
rev[lc] ^= 1; rev[rc] ^= 1; rev[x] = 0;
swap(c[x][0], c[x][1]);
//之前看到c[x][0/1]有重复,就用lc,rc减少代码量
//事实上不能写swap(lc,rc)
}
}
void update(int x) {
if (!isroot(x)) update(fa[x]);
pushdown(x);
}
void rotate(int x) {
int y = fa[x], z = fa[y], k = get(x);
if (!isroot(y)) c[z][y == c[z][1]] = x;
c[y][k] = c[x][!k]; fa[c[x][!k]] = y;
c[x][!k] = y; fa[y] = x; fa[x] = z;
pushup(y); pushup(x);
}
void splay(int x) {
update(x);
for (int par; par = fa[x], !isroot(x); rotate(x)) {
if (!isroot(par)) rotate(get(par) == get(x) ? par : x);
}
}
void access(int x) {
for (int y = 0; x; y = x, x = fa[x]) {
splay(x); c[x][1] = y; pushup(x);
}
}
void makeroot(int x) {
access(x); splay(x); rev[x] ^= 1;
}
void link(int x, int y) {
makeroot(x); fa[x] = y;
}
void split(int x, int y) {
makeroot(x); access(y); splay(y);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; ++i) {
int x, y; char ch; scanf("%d%d%d %c", &x, &y, w + n + i, &ch);
link(x, n + i); link(n + i, y);
}
int q; scanf("%d", &q);
while (q--) {
int x, y; scanf("%d%d", &x, &y);
split(x, y);
printf("%d\n", dis[y]);
}
return 0;
}