Poj 1988 cube stacking

Source: Internet
Author: User

Question: The number is 1 ~ N blocks, two operations

  1. M x Y: Stack block X on the heap where block y is located.
  2. C x ask how many blocks are under block x

The Code cleverly compresses the path in the getparent function, and calculates the under value corresponding to the block.

This requires a good understanding

 

 1 //#define LOCAL 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6  7 const int maxn = 30000 + 10; 8 int parent[maxn], under[maxn], sum[maxn]; 9 10 int GetParent(int a)11 {12     if(parent[a] == a)13         return a;14     int t = GetParent(parent[a]);15     under[a] += under[parent[a]];16     parent[a] = t;17     return t;18 }19 20 void Merge(int a, int b)21 {22     int pa = GetParent(a);23     int pb = GetParent(b);24     if(pa == pb)    return;25     parent[pb] = pa;26     under[pb] = sum[pa];27     sum[pa] += sum[pb];28 }29 30 int main(void)31 {32     #ifdef LOCAL33         freopen("1988in.txt", "r", stdin);34     #endif35 36     for(int i = 1; i < maxn; ++i)37     {38         parent[i] = i;39         under[i] = 0;40         sum[i] = 1;41     }42     int n;43     scanf("%d", &n);44     getchar();45     for(int i = 0; i < n; ++i)46     {47         char p;48         scanf("%c", &p);49         if(p == ‘M‘)50         {51             int a, b;52             scanf("%d%d", &a, &b);53             getchar(); 54             Merge(b, a);55         }56         else57         {58             int a;59             scanf("%d", &a);60             getchar();61             GetParent(a);62             printf("%d\n", under[a]);63         }64     }65     return 0;66 }
Code Jun

 

Poj 1988 cube stacking

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.