Http://poj.org/problem? Id = 1984
The question is so painful...
Link and query set, use the Cx and Cy arrays to record the relative location of the point and the root node, and merge them according to the input. When the query is made, the distance is calculated. If the query is not in the same set, the relative location cannot be determined.
Code:
# Include <cstdio>
# Include <cstring>
Int P [40001], CX [40001], CY [40001];
Int F1 [10001], F2 [10001], FI [10001];
Struct edge {
Int S, E, L;
Char D;
} Q [2, 40001];
Int ABS (int ){
Return a> 0? A:-;
}
Void make_set (int n ){
For (INT I = 0; I <= n + 1; I ++ ){
P [I] = I;
CX [I] = CY [I] = 0;
}
}
Int find_set (int x ){
Int temp;
If (X! = P [x]) {
Temp = P [x];
P [x] = find_set (P [x]);
CX [x] = Cx [temp] + cx [x];
CY [x] = CY [temp] + cy [x];
}
Return P [x];
}
Void union_set (int x ){
Int A = Q [X]. S;
Int B = Q [X]. E;
Int Pa = find_set ();
Int Pb = find_set (B );
P [Pb] = PA;
CX [Pb] = Cx [a]-cx [B];
CY [Pb] = CY [a]-cy [B];
Switch (Q [X]. d ){
Case 'E': Cx [Pb] + = Q [X]. L; break;
Case 'W': Cx [Pb]-= Q [X]. L; break;
Case 'N': CY [Pb] + = Q [X]. L; break;
Case's ': CY [Pb]-= Q [X]. L; break;
}
Return;
}
Int main (){
Int n, m, K, I, j, t, x, y, z, TX, Ty;
While (~ Scanf ("% d", & N, & M )){
Make_set (N );
For (I = 1; I <= m; I ++)
Scanf ("% d % C", & Q [I]. s, & Q [I]. e, & Q [I]. l, & Q [I]. d );
Scanf ("% d", & T );
For (I = 0; I <t; I ++)
Scanf ("% d", & F1 [I], & F2 [I], & fi [I]);
Int temp = 0;
For (I = 1; I <= m; I ++ ){
Tx = find_set (Q [I]. s );
Ty = find_set (Q [I]. E );
If (TX! = Ty)
Union_set (I );
While (FI [temp] = I ){
Tx = find_set (F1 [temp]);
Ty = find_set (F2 [temp]);
If (TX! = Ty) printf ("-1 \ n ");
Else {
Tx = ABS (CX [F1 [temp]-cx [F2 [temp]);
Ty = ABS (CY [F1 [temp]-cy [F2 [temp]);
Printf ("% d \ n", Tx + ty );
}
Temp ++;
}
}
}
Return 0 ;}