hdu 3172 Virtual Friends (並查集 + 字典樹)

來源:互聯網
上載者:User

標籤:blog   http   資料   2014   os   代碼   

題目:

        連結:點擊開啟連結

題意:

        輸入n,給出n行資料,每行有兩個字串,輸出關係網路中朋友的個數,n行。

思路:

        

代碼:

#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;const int N = 22;const int M = 200020;struct node{    int c;    node *child[52];    node()    {        c = 0;        for(int i=0; i<52; i++)            child[i] = NULL;    }}*root1;int n;int cnt;int root[M];char stra[N],strb[N];int insertTrie(char s[])//字典樹功能:將名字映射成代表該名字的一個整數{    node *p = root1;    int len = strlen(s);    for(int k,i=0; i<len; i++,p=p->child[k])    {        if(s[i] >= 'a' && s[i] <= 'z')            k = s[i] - 'a';        else            k = s[i] - 'A' + 26;        if(!p->child[k])            p->child[k] = new node();    }    if(p->c)        return p->c;    return p->c = ++cnt;}void init(){    for(int i=0; i<M; i++)        root[i] = -1;}int findset(int x){    int r;    for(r=x; root[r]>0; r=root[r]);    while(r != x)    {        int temp = root[x];        root[x] = r;        x = temp;    }    return r;}int mergeset(int r1,int r2){    int temp = root[r1] + root[r2];    if(root[r1] > root[r2])    {        root[r1] = r2;        root[r2] = temp;    }    else    {        root[r2] = r1;        root[r1] = temp;    }    return temp;}void dealTrie(node *p){    for(int i=0; i<52; i++)    {        if(p->child[i])            dealTrie(p->child[i]);    }    delete p;    p = NULL;}int main(){    //freopen("input.txt","r",stdin);    int t;    while(scanf("%d",&t) != EOF)    {        while(t--)        {            scanf("%d",&n);            getchar();            cnt = 0;            init();            root1 = new node();            for(int i=0; i<n; i++)            {                scanf("%s%s",stra,strb);                int x = insertTrie(stra);                int y = insertTrie(strb);                int fx = findset(x);                int fy = findset(y);                if(fx != fy)                    printf("%d\n",abs(mergeset(fx,fy)));                else                    printf("%d\n",abs(root[fx]));            }            dealTrie(root1);        }    }    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.