hdu 2818 Building Block(帶權並查集)

來源:互聯網
上載者:User

標籤:style   blog   http   2014   os   代碼   

題目:

        連結:點擊開啟連結

題意:

        有N個積木,1到N編號。進行一些操作P次,M:X Y把X積木放到Y的上面,如果X和Y相等請忽略。C:X 計算X積木下的積木數目。

思路:

        帶權並查集的題目,定義數組sum[i]表示i積木下面積木的數目。遇到操作M,就把X和Y合并到同一個集合中。我們視每個結點為1個 Pile,其中rank[i]就表示每個Pile處的積木的個數,Initially, there are N piles, and each pile contains one block.所以,rank[]的初始值應該是1。

代碼:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int N = 30030;int root[N];int sum[N],rank[N];int q;int findset(int x){    if(x == root[x])        return x;    int temp = findset(root[x]);    sum[x] += sum[root[x]];    return root[x] = temp;}void mergeset(int x,int y){    int fx = findset(x);    int fy = findset(y);    if(fx == fy)        return ;    root[fx] = fy;    sum[fx] += rank[fy];//sum    rank[fy] += rank[fx];//每進行一次M操作,rank的值都要更新。}void init(){    for(int i=0; i<=30000; i++)    {        root[i] = i;        rank[i] = 1;        sum[i] = 0;    }}int main(){    //freopen("input.txt","r",stdin);    char ch;    int x,y,z;    while(scanf("%d",&q) != EOF)    {        init();        getchar();        while(q--)        {            scanf("%c",&ch);            getchar();            if(ch == 'M')            {                scanf("%d%d",&x,&y);                mergeset(x,y);            }            else            {                scanf("%d",&z);                findset(z);                printf("%d\n",sum[z]);            }            getchar();        }    }    return 0;}
---------------------------------------------------------------

戰鬥,從不退縮;奮鬥,永不停歇~~~~~~~~

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.