并查集-HDU-1213-How Many Tables

来源:互联网 发布:python 余弦相似度 编辑:程序博客网 时间:2024/05/21 21:46

How Many Tables

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20880 Accepted Submission(s): 10333

Problem Description
Today 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.

Input
The 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.

Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.

Sample Input
2
5 3
1 2
2 3
4 5

5 1
2 5

Sample Output
2
4

Author
Ignatius.L

Source
杭电ACM省赛集训队选拔赛之热身赛


题意:
那谁要过生日,现在请朋友来吃饭,但是只有互相认识的朋友才愿意坐在同一桌,于是请问最少需要多少张桌子?
如果A认识B,B认识C,那么A,B,C就是互相认识的。


题解:
很明显的并查集。。。拿来写博客完全是为了赶着2月来到之前满4篇。。。
直接将认识的人合并集合,最后看有多少个连通分量就行了。


////  main.cpp//  并查集-C-How Many Tables////  Created by 袁子涵 on 16/1/31.//  Copyright © 2016年 袁子涵. All rights reserved.////  0ms    1784kb#include <iostream>#include <cstring>#include <cstdio>#include <cstdlib>#include <cmath>#include <algorithm>#include <vector>#include <queue>using namespace std;int T,n,m;int set[1005],stk[1005];bool vis[1005];int find(int num){    int now=num,top=0;    while (set[now]!=now)    {        stk[top++]=now;        now=set[now];    }    while (top)        set[stk[--top]]=now;    return now;}void join(int num1,int num2){    int f1=find(num1),f2=find(num2);    set[f1]=set[f2];}int main(int argc, const char * argv[]) {    scanf("%d",&T);    while (T--) {        int total=0;        scanf("%d%d",&n,&m);        for (int i=1; i<=n; i++)        {            set[i]=i;            vis[i]=0;        }        int a,b;        for (int i=1; i<=m; i++) {            scanf("%d%d",&a,&b);            join(a, b);        }        for (int i=1; i<=n; i++)            vis[find(i)]=1;        for (int i=1; i<=n; i++) {            if (vis[i]) {                total++;            }        }        cout << total << endl;    }    return 0;}
0 0