forked from nanwan03/poj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1984 Navigation Nightmare.java
104 lines (100 loc) · 2.33 KB
/
1984 Navigation Nightmare.java
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
100
101
102
103
104
import java.io.*;
import java.util.*;
class Node {
Node root;
int index;
int distX;
int distY;
Node(int index) {
this.root = this;
this.index = index;
this.distX = 0;
this.distY = 0;
}
}
class Path {
Node u;
Node v;
int len;
char dir;
Path(Node u, Node v, int len, char dir) {
this.u = u;
this.v = v;
this.len = len;
this.dir = dir;
}
}
class Query {
Node u;
Node v;
int index;
Query(Node u, Node v, int index) {
this.u = u;
this.v = v;
this.index = index;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nodeNum = in.nextInt();
int pathNum = in.nextInt();
Node[] farm = new Node[nodeNum + 1];
for (int i = 0; i <= nodeNum; ++i) {
farm[i] = new Node(i);
}
Path[] paths = new Path[pathNum];
for (int i = 0; i < pathNum; ++i) {
paths[i] = new Path(farm[in.nextInt()], farm[in.nextInt()], in.nextInt(), in.next().charAt(0));
}
int queryNum = in.nextInt();
Query[] queries = new Query[queryNum];
for (int i = 0; i < queryNum; ++i) {
queries[i] = new Query(farm[in.nextInt()], farm[in.nextInt()], in.nextInt());
}
int cur = 0;
for (int i = 0; i < queryNum; ++i) {
while (cur < queries[i].index) {
union(paths[cur++]);
}
if (find(queries[i].u).index != find(queries[i].v).index) {
System.out.println("-1");
} else {
int dist = Math.abs(queries[i].u.distX - queries[i].v.distX) +
Math.abs(queries[i].u.distY - queries[i].v.distY);
System.out.println(dist);
}
}
}
private static Node find(Node node) {
if (node.index == node.root.index) {
return node;
}
Node temp = node.root;
node.root = find(node.root);
node.distX += temp.distX;
node.distY += temp.distY;
return node.root;
}
private static void union(Path p) {
Node rootU = find(p.u);
Node rootV = find(p.v);
if (rootU.index == rootV.index) {
return;
}
rootV.root = rootU;
if (p.dir == 'E') {
rootV.distX = p.u.distX - p.v.distX + p.len;
rootV.distY = p.u.distY - p.v.distY;
} else if (p.dir == 'W') {
rootV.distX = p.u.distX - p.v.distX - p.len;
rootV.distY = p.u.distY - p.v.distY;
} else if (p.dir == 'N') {
rootV.distX = p.u.distX - p.v.distX;
rootV.distY = p.u.distY - p.v.distY + p.len;
} else {
rootV.distX = p.u.distX - p.v.distX;
rootV.distY = p.u.distY - p.v.distY - p.len;
}
}
}