知识点:离线,并查集
这个题是离线思想+边带权并查集练习题,感觉是有蓝题难度的,但是前面写过一个离线并查集了,这个题做着就比较手熟,23分钟一次过了这个题,这个题并没有什么亮点,题目的问法就是提示你这个题要用离线,然后带权并查集也只是多了一个权,本质上没有什么区别,所以还是很快就过了这个题
#include <bits/stdc++.h>
using namespace std;
const int N = 4e5 + 5;
struct node {
int x, y, line, rank;
} e[N];
int fa[N], h[N], w[N], a[N], b[N], c[N];
char dir[N];
int get(int x) {
if (x == fa[x]) return x;
int root = get(fa[x]);
h[x] += h[fa[x]];
w[x] += w[fa[x]];
return fa[x] = root;
}
void merge(int x, int y, int dist, char dir) {
int fx = get(x), fy = get(y);
fa[fy] = fx;
if (dir == 'N') {
h[fy] = h[x] - h[y] - dist;
w[fy] = w[x] - w[y];
} else if (dir == 'S') {
h[fy] = h[x] - h[y] + dist;
w[fy] = w[x] - w[y];
} else if (dir == 'W') {
h[fy] = h[x] - h[y];
w[fy] = w[x] - w[y] - dist;
} else {
h[fy] = h[x] - h[y];
w[fy] = w[x] - w[y] + dist;
}
}
bool cmp(node a, node b) {
return a.line < b.line;
}
int main() {
for (int i = 0; i < N; i++) fa[i] = i;
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d %c", a + i, b + i, c + i, dir + i);
}
int k;
cin >> k;
for (int i = 1; i <= k; i++) {
scanf("%d%d%d", &e[i].x, &e[i].y, &e[i].line);
e[i].rank = i;
}
sort(e + 1, e + k + 1, cmp);
int ans[N];
int ind = 1;
for (int i = 1; i <= k; i++) {
while (ind <= m && ind <= e[i].line) {
merge(a[ind], b[ind], c[ind], dir[ind]);
ind++;
}
int x1 = e[i].x, y1 = e[i].y;
if (get(x1) != get(y1)) ans[e[i].rank] = -1;
else ans[e[i].rank] = abs(h[x1] - h[y1]) + abs(w[x1] - w[y1]);
}
for (int i = 1; i <= k; i++) printf("%d\n", ans[i]);
return 0;
}