hdu 1213 How Many Tables(並查集)

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   os   io   for   

Problem DescriptionToday is Ignatius‘ birthday. He invites a lot of friends. Now it‘s dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.InputThe input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.OutputFor each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.Sample Input
25 31 22 34 55 12 5
Sample Output
24

思路:裸的並查集
 1 #include<iostream> 2 #include<stdio.h> 3 #include<string.h> 4 #include<stdlib.h> 5 #include<math.h> 6 #include<algorithm> 7 #define LL long long 8 #define mod 1e9 + 7 9 const int M = 1005;10 11 using namespace std;12 13 struct node{14     int x;15     int y;16 }a[M];17 18 int cun[M];19 20 int find(int x)21 {22     return cun[x] == x ? x : cun[x] = find(cun[x]);23 }24 25 void shu(int x, int y)26 {27     int p = find(x);28     int q = find(y);29     cun[p] = q;30 }31 32 int main()33 {34     int n, m;35     int t;36     cin >> t;37     while( t-- )38     {39         cin >> n >> m;40         for(int i = 1; i <= m; ++i)41             cin >> a[i].x >> a[i].y;42         for(int i = 0; i <= n; ++i)43             cun[i] = i;44         int cnt = 0;45         for(int i = 1; i <= m; ++i)46         {47             if(find(a[i].x) != find(a[i].y))48             {49                 cnt++;50                 shu(a[i].x,a[i].y);51             }52         }53         cout << n - cnt << endl;54     }55     return 0;56 }
View Code

 

聯繫我們

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