首页 > 学院 > 开发设计 > 正文

HDU1213 How Many Tables(并查集)

2019-11-06 06:43:28
字体:
来源:转载
供稿:网友

题目:

How Many Tables

Time Limit: 2000/1000 MS (java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 27756    Accepted Submission(s): 13779PRoblem 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 AuthorIgnatius.L Source杭电ACM省赛集训队选拔赛之热身赛 RecommendEddy   |   We have carefully selected several similar problems for you:  1856 1325 1198 1863 1102  
Statistic | Submit | Discuss | Note
思路:

简单并查集,不多说~

代码:

#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>#include <string>#include <iostream>#include <stack>#include <queue>#include <vector>#include <algorithm>#define mem(a,b) memset(a,b,sizeof(a))#define N 1000+20#define M 30000+20#define MOD 1000000000+7#define inf 0x3f3f3f3fusing namespace std;int n,m;int pre[N];void init(){    for(int i=1; i<=n; i++)        pre[i]=i;}int find(int x){    if(x==pre[x])        return x;    else    {        pre[x]=find(pre[x]);        return pre[x];    }}void mix(int x,int y){    int fx=find(x);    int fy=find(y);    if(fx!=fy)        pre[fy]=pre[x];}int main(){    int t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&m);        init();        int a,b;        for(int i=1; i<=m; i++)        {            scanf("%d%d",&a,&b);            mix(a,b);        }        int sum=0;        for(int i=1; i<=n; i++)            if(pre[i]==i)                sum++;        printf("%d/n",sum);    }    return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表