Uvaliva3027 (query set)

Source: Internet
Author: User

Uvaliva3027 (query set)

Question:

For Iuv, the parent node of u is set to v, and the distance from u to v is | u-v | % 1000;

If Eu is used, the distance from u to the root is output;

O end;

 

Ideas:

In the merge phase, it is a common query set, but you still need to calculate a distance:

However, the distance should be accumulated and recorded during each query:

 

AC code:

 

#include
 
  #include
  
   #include
   
    using namespace std;const int N = 20000 + 5;int p[N];int dis[N];int n;void init(int n) {for(int i = 0; i <= n; i++) {p[i] = i;dis[i] = 0;}return ;}int find_parent(int x) {if(x != p[x]) {int r = find_parent(p[x]);dis[x] += dis[p[x]];return p[x] = r;}return x;}void Union(int u, int v) {p[u] = v;dis[u] = abs(u - v);dis[u] %= 1000;}int main() {int t;scanf("%d",&t);while(t--) {scanf("%d",&n);init(n);char c;while(1) {getchar();c = getchar();if(c == 'I') {int a,b;scanf("%d%d",&a,&b);Union(a,b);}else if(c == 'E') {int a;scanf("%d",&a);find_parent(a);printf("%d\n",dis[a]);}elsebreak;}}}
   
  
 


 

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.