Usaco's monthly competition question.
Record the relative distance between two points in the x and y directions, and use the query set for maintenance.
If we compare it with the poj 1182 food chain, we will find the similarity between the path compression part and the merged part.
Therefore, it is not difficult to query a set. There are certain procedures to follow. You must make a summary.
[Code]
[Cpp]
# Include <iostream>
# Include <cstring>
# Include <string>
# Include <cstdio>
# Include <algorithm>
Using namespace std;
Const int N = 40005, K = 10005;
Struct node
{
Int x, y, idx, n;
} A [K];
Int x [N], y [N], dx [N], dy [N], rx [N], ry [N], ans [K], fa [N];
Int n, m, k;
Int find (int x)
{
If (fa [x] = x) return x;
Int t = fa [x];
Fa [x] = find (fa [x]);
Rx [x] + = rx [t];
Ry [x] + = ry [t];
Return fa [x];
}
Int cmp (node a, node B)
{
Return a. idx <B. idx;
}
Int main ()
{
Int I, j, d, fx, fy;
Char c;
Freopen ("in", "r", stdin );
Scanf ("% d", & n, & m );
For (I = 1; I <= n; I ++)
{
Fa [I] = I;
Rx [I] = ry [I] = 0;
}
For (I = 1; I <= m; I ++)
{
Scanf ("% d % c", & x [I], & y [I], & d, & c );
Switch (c)
{
Case 'W': dx [I] =-d; dy [I] = 0; break;
Case's ': dx [I] = 0; dy [I] =-d; break;
Case 'E': dx [I] = d; dy [I] = 0; break;
Case 'N': dx [I] = 0; dy [I] = d; break;
}
}
Scanf ("% d", & k );
For (I = 1; I <= k; I ++)
{
Scanf ("% d", & a [I]. x, & a [I]. y, & a [I]. idx );
A [I]. n = I;
}
Sort (a + 1, a + k + 1, cmp );
J = 1;
For (I = 1; I <= k; I ++)
{
For (; j <= a [I]. idx; j ++)
{
Fx = find (x [j]); fy = find (y [j]);
Fa [fy] = fx;
Rx [fy] = rx [x [j]-rx [y [j]-dx [j];
Ry [fy] = ry [x [j]-ry [y [j]-dy [j];
}
If (find (a [I]. x )! = Find (a [I]. y ))
Ans [a [I]. n] =-1;
Else
Ans [a [I]. n] = abs (rx [a [I]. x]-rx [a [I]. y]) + abs (ry [a [I]. x]-ry [a [I]. y]);
}
For (I = 1; I <= k; I ++)
Printf ("% d \ n", ans [I]);
}
Author: ascii991