Title Source: POJ 1984 Navigation Nightmare
Test instructions: give you a tree K-times ask for a Manhattan distance between 2 points and have to start with a K-bar
Idea: In accordance with the direction of the upper left corner of the root of the top left corner is the origin dx[i] for I point distance root x coordinate dy[] is the Y coordinate two can be obtained by path compression is only two-dimensional
#include <cstdio> #include <cstdlib> #include <cstring>using namespace std;const int maxn = 40010;int f[ MAXN], DX[MAXN], dy[maxn];struct node{int u, V, W;char s[3];} A[maxn];void init (int n) {for (int i = 1; I <= n; i++) F[i] = i;memset (dx, 0, sizeof (DX)), memset (dy, 0, sizeof (DY));} int find (int x) {if (x! = F[x]) {int rt = find (F[x]);d x[x] + = dx[f[x]];d y[x] + = dy[f[x]];f[x] = Rt;return RT;} return x;} int main () {int n, m;scanf ("%d%d", &n, &m), Init (n), for (int i = 1; I <= m; i++) {scanf ("%d%d%d%s", &a[i].u , &A[I].V, &A[I].W, A[I].S);} int q;scanf ("%d", &q); int i = 1;while (q--) {int S, E, w;scanf ("%d%d%d", &s, &e, &w); while (I <= M & & I <= w) {int u = a[i].u;int v = a[i].v;int x = Find (u), int y = find (v), if (x = = y) continue;if (a[i].s[0] = = ' E ') {f[y ] = X;dx[y] = Dx[u]-dx[v]+a[i].w;dy[y] = Dy[u]-dy[v];} else if (a[i].s[0] = = ' W ') {f[x] = y;dx[x] = dx[v]-dx[u]+a[i].w;dy[x] = Dy[v]-dy[u];} else if (a[i].s[0] = = ' N ') {f[x] = y;dy[x] = dy[V]-dy[u]+a[i].w;dx[x] = Dx[v]-dx[u];} Else{f[y] = X;dy[y] = Dy[u]-dy[v]+a[i].w;dx[y] = Dx[u]-dx[v];} i++;} int x = find (s), int y = Find (E), if (x = = y) {int d = ABS (Dx[s]-dx[e]) + ABS (Dy[s]-dy[e]);p rintf ("%d\n", d);} Else{puts ("1");}} return 0;}