维护东西南北的差值,相当于维护两个并查集
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX_N 50010
#define sci(num) scanf("%d",&num)
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
#define MOD 3
int fa[MAX_N], rx[MAX_N],ry[MAX_N];
int N,M,K;
struct que{
int x,y,d;
char ch;
} qs[40010];
int Find(int x) {
if (fa[x] != x) {
int p = fa[x];
fa[x] = Find(fa[x]);
rx[x] += rx[p];
ry[x] += ry[p];
}
return fa[x];
}
void init() {
for (int i = 0;i <= N;i++) {
fa[i] = i;
rx[i] = ry[i] = 0;
}
}
void Union(int x,int y,int d,char ch) {
int fx = Find(x);
int fy = Find(y);
if (ch == 'E' || ch == 'W') {
if (fx != fy) {
rx[fy] = rx[x] - (d + rx[y]);
ry[fy] = ry[x] - ( ry[y]);
fa[fy] = fx;
}
} else if (ch == 'N' || ch == 'S') {
if (fx != fy) {
rx[fy] = rx[x] - ( rx[y]);
ry[fy] = ry[x] - ( d + ry[y]);
fa[fy] = fx;
}
}
}
int main() {
sci(N); sci(M);
init();
for (int i = 0;i < M;i++) {
scanf("%d %d %d %c\n",&qs[i].x,&qs[i].y,&qs[i].d,&qs[i].ch);
if (qs[i].ch == 'W') qs[i].d= -qs[i].d;
if (qs[i].ch == 'S') qs[i].d = -qs[i].d;
}
int now = 0;
sci(K);
for (int i = 0;i < K;i++) {
int x,y,w;
sci(x); sci(y); sci(w);
for (;now < w;now++) {
Union(qs[now].x,qs[now].y,qs[now].d,qs[now].ch);
}
int fx = Find(x);
int fy = Find(y);
if (fx != fy) {
printf("-1\n");
} else {
printf("%d\n",abs(rx[x] - rx[y]) + abs(ry[x] - ry[y]));
}
}
return 0;
}