POJ 1984. Navigation Nightmare

链接

http://poj.org/problem?id=1984

题意

有 $n$ 个农田,$m$ 个关系

每个关系给出 $b$ 到 $a$ 的曼哈顿距离以及 $b$ 对 $a$ 的方向(正南或正北或正西或正东)

有$k$ 次询问,问在给出前 $c$ 个关系后能否计算出 $a$ 至 $b$ 的曼哈顿距离距离,能就输出曼哈顿距离距离,不能输出 $-1$

思路

因为求的是曼哈顿距离并且方向为正南或正北或正西或正东,所以我们可以用并查集维护所有有关系的点,并建立边权来维护每个点的坐标(根的坐标为 $(0,0)$)

对于询问,两点如果在一个集合内,直接计算曼哈顿距离即可,否则输出 $-1$

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<climits>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<map>
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(),(x).end()
#define PB push_back
#define MP make_pair
#define FI first
#define SE second
using namespace std;
typedef double DB;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector<PII> VPII;
//head
const int N=10005;
int dx[N<<2],dy[N<<2],fa[N<<2],res[N];
struct R {
int a,b,l;
char d;
R() {}
R(int a,int b,int l,char d):a(a),b(b),l(l),d(d) {}
}r[N<<2];
struct Q {
int a,b,c,id;
Q() {}
Q(int a,int b,int c,int id):a(a),b(b),c(c),id(id) {}
bool operator < (const Q &a) const {
return c<a.c;
}
}q[N];
int find(int x) {
if(x==fa[x]) return x;
int root=find(fa[x]);
dx[x]+=dx[fa[x]];
dy[x]+=dy[fa[x]];
return fa[x]=root;
}
int main() {
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=m;i++) {
int a,b,l;
char s[2];
scanf("%d%d%d%s",&a,&b,&l,s);
r[i]=R(a,b,l,s[0]);
}
int k;
scanf("%d",&k);
for(int i=1;i<=k;i++) {
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
q[i]=Q(a,b,c,i);
}
sort(q+1,q+1+k);
int cnt=1;
for(int i=1;i<=m;i++) {
int x=r[i].a,y=r[i].b;
int tx=find(x),ty=find(y);
fa[tx]=ty;
if(r[i].d=='N') {
dx[tx]=dx[y]-dx[x];
dy[tx]=dy[y]-dy[x]+r[i].l;
} else if(r[i].d=='S') {
dx[tx]=dx[y]-dx[x];
dy[tx]=dy[y]-dy[x]-r[i].l;
} else if(r[i].d=='E') {
dx[tx]=dx[y]-dx[x]+r[i].l;
dy[tx]=dy[y]-dy[x];
} else if(r[i].d=='W') {
dx[tx]=dx[y]-dx[x]-r[i].l;
dy[tx]=dy[y]-dy[x];
}
while(q[cnt].c==i) {
int tx=find(q[cnt].a),ty=find(q[cnt].b);
if(tx!=ty) {
res[q[cnt].id]=-1;
} else {
res[q[cnt].id]=abs(dx[q[cnt].a]-dx[q[cnt].b])+abs(dy[q[cnt].a]-dy[q[cnt].b]);
}
++cnt;
}
}
for(int i=1;i<=k;i++) printf("%d\n",res[i]);
return 0;
}