HDU 3172 Virtual Friends(帶權並查集),hdu3172

來源:互聯網
上載者:User

HDU 3172 Virtual Friends(帶權並查集),hdu3172

題目地址:HDU 3172

帶權並查集水題。每次合并的時候維護一下權值。注意坑爹的輸入。。

代碼如下:

#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;#define LL long longint bin[210000], num[210000];int find1(int x){    return bin[x]==x?x:bin[x]=find1(bin[x]);}void join(int x, int y){    int f1=find1(x);    int f2=find1(y);    if(f1!=f2)    {        bin[f2]=f1;        num[f1]+=num[f2];        printf("%d\n",num[f1]);    }    else        printf("%d\n",num[f2]);}int main(){    int t, n, i, cnt;    char s1[30], s2[30];    map<string,int>q;    while(scanf("%d",&t)!=EOF)    {        while(t--)        {            scanf("%d",&n);            for(i=1; i<210000; i++)            {                bin[i]=i;                num[i]=1;            }            q.clear();            cnt=1;            while(n--)            {                getchar();                scanf("%s%s",s1,s2);                if(!q[s1])                    q[s1]=cnt++;                if(!q[s2])                    q[s2]=cnt++;                join(q[s1],q[s2]);            }        }    }    return 0;}



HDU 3172 Virtual Friends 並查集

多組資料
有點坑爹

需要用
while(scanf( "%d" , &t )!=EOF)
while(t--)

而且需要對名字進行hash或者建立二叉搜尋
不然太慢
 
HDU 杭電 acm 3172 Virtual Friends 並查集逾時了,最佳化

。。。又是你。。。
你字串是儲存在一個數組中的吧?
你尋找的時候好像是線性尋找
最佳化的話
可以每次加入一個字串時把字串排序用nlogn的演算法排序
然後讀下個一字串 二分尋找這個串 如果不在現有的字串中就又添加一個後又排序.

還有就是可以用到庫函數映射 這個最好不要嘗試. 基礎打好
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.