Uva 793 Network Connections

來源:互聯網
上載者:User

標籤:style   blog   io   color   ar   os   sp   for   資料   

題目意思是有幾台電腦,c開頭的行是兩個電腦相連,q開頭是查詢兩個是否相連。

思路:並查集。

題目應該可以有幾組輸入,這是我在algorithm網站上找的範例:

輸入:

2

10
c 1 5
c 2 7
q 7 1
c 3 9
q 9 6
c 2 5
q 7 5

10
c 1 5
c 2 7
q 7 1
c 3 9
q 9 6
c 2 5
q 7 5

輸出:

1,2

 

1,2

 1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #define MAX 100001 6 using namespace std; 7  8 int Computer; 9 typedef struct node{10     int data_;//節點對應人的編號11     int rank_;//節點對應的秩12     int parent_;//節點對應雙親下標13 }UFSTree;14 void MAKE_SET(UFSTree t[]);//初始化並查集樹15 int FIND_SET(UFSTree t[],int x);//在x所在子樹中尋找集合編號16 void UNION(UFSTree t[],int x,int y);//將x和y所在的子樹合并17 int main()18 {19     #ifndef ONLINE_JUDGE20         freopen("D:\\acm.txt","r",stdin);21     #endif // ONLINE_JUDGE22     int success,unsuccess;23     char testCase[100];//數組要開的大一些,否則會re24     int caseNum;25     cin>>caseNum;26     while(caseNum--){27         cin>>Computer;28         success = unsuccess = 0;29         UFSTree t[MAX];30         MAKE_SET(t);31         getchar();32         while(gets(testCase)){33             if(testCase[0] == 0)break;34             int x,y;35             sscanf(testCase + 1, "%d%d",&x,&y);//要用輸入資料流,用數組提取會wa36             int xx = FIND_SET(t,x),yy = FIND_SET(t,y);37             if(testCase[0] == ‘c‘){38                 if(xx != yy )UNION(t,x,y);39             }40             if(testCase[0] == ‘q‘){41                 if(xx != yy)unsuccess ++;42                 else success ++;43             }44         }45         cout<<success<<","<<unsuccess<<endl;46         if(caseNum)cout<<endl;47     }48     return 0;49 }50 void MAKE_SET(UFSTree t[]){51     for(int i = 1;i <= Computer;i++){52         t[i].data_ = i;//資料為該人編號53         t[i].rank_ = 1;//秩,即節點的個數54         t[i].parent_ = i;//父節點指向自己55     }56 }57 int FIND_SET(UFSTree t[],int x){58     if(x != t[x].parent_){59         return (FIND_SET(t,t[x].parent_));60     }61     else62         return x;63 }64 void UNION(UFSTree t[],int x,int y){65     x = FIND_SET(t,x);66     y = FIND_SET(t,y);67     if(x==y)return;68     if(t[x].rank_ > t[y].rank_){69             t[y].parent_ = x;70             t[x].rank_ += t[y].rank_;71     }72     else{73         t[x].parent_ = y;74         t[y].rank_ += t[x].rank_;75     }76 }

 

Uva 793 Network Connections

聯繫我們

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