And query set exercises --- poj 1984

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.