题意:有多个点,在平面上位于坐标点上,给出一些关系,表示某个点在某个点的正东/西/南/北方向多少距离,然后给出一系列询问,表示在第几个关系给出后询问某两点的曼哈顿距离,或者未知则输出-1。
在权值上保存两个值 : 与祖先在两个方向的差。直接带权并查集
离线数据再处理。
链接:poj 1984
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <vector>
#include <sstream>
#define ll long long
using namespace std;
const int maxn = 100000 + 10;
const int inf = 0x3f3f3f3f;
int father[maxn];
int eh[maxn], nh[maxn];
int a[maxn], b[maxn], l[maxn];
char s[maxn][5];
int n, m, k;
int ans[maxn];
struct node {
int a, b;
int num;
int t;
friend bool operator < (node a, node b) {
return a.t < b.t;
}
}q[maxn];
void init() {
for(int i = 0; i <= n; i++) {
father[i] = i;
eh[i] = nh[i] = 0;
}
}
int getf(int x) {
if(father[x] == x) return x;
int rx = father[x];
father[x] = getf(father[x]);
nh[x] += nh[rx];
eh[x] += eh[rx];
return father[x];
}
int main()
{
while(~scanf("%d %d", &n, &m)) {
for(int i = 1; i <= m; i++) {
scanf("%d %d %d %s", &a[i], &b[i], &l[i], s[i]);
}
scanf("%d", &k);
for(int i = 1; i <= k; i++) {
scanf("%d %d %d", &q[i].a, &q[i].b, &q[i].t);
q[i].num = i;
}
sort(q + 1, q + k + 1);
init();
int res = 1;
for(int i = 1; i <= m; i++) {
int x = getf(a[i]), y = getf(b[i]);
int nl = 0, el = 0;
if(s[i][0] == 'N') nl = l[i];
else if(s[i][0] == 'S') nl = -l[i];
else if(s[i][0] == 'E') el = l[i];
else el = -l[i];
if(x != y) {
father[x] = y;
nh[x] = nh[b[i]] + nl - nh[a[i]];
eh[x] = eh[b[i]] + el - eh[a[i]];
}
while(q[res].t == i && res <= k) {
x = getf(q[res].a), y = getf(q[res].b);
if(x != y) {
ans[q[res].num] = -1;
}
else {
ans[q[res].num] = abs(nh[q[res].a] - nh[q[res].b]) + abs(eh[q[res].a] - eh[q[res].b]);
}
res++;
}
}
for(int i = 1; i <= k; i++) {
printf("%d\n", ans[i]);
}
}
return 0;
}