并查集-水题

来源:互联网 发布:python 字典转列表 编辑:程序博客网 时间:2024/05/22 08:07

问题 I: How Many Tables

时间限制1 Sec  内存限制32 MB提交14  解决8[提交][状态][讨论版]

题目描述

Today is Ignatius' birthday. He invitesa lot of friends. Now it's dinner time. Ignatius wants to know how many tableshe 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 isthat if I tell you A knows B, and B knows C, that means A, B, C know eachother, so they can stay in one table.

For example: If I tell you A knows B, Bknows C, and D knows E, so A, B, C can stay in one table, and D, E have to stayin the other one. So Ignatius needs 2 tables at least.

输入

The input starts with an integerT(1<=T<=25) which indicate the number of test cases. Then T test casesfollow. Each test case starts with two integers N and M(1<=N,M<=1000). Nindicates the number of friends, the friends are marked from 1 to N. Then Mlines follow. Each line consists of two integers A and B(A!=B), that meansfriend A and friend B know each other. There will be a blank line between twocases.

输出

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

样例输入

2

6 4

1 2

2 3

3 4

1 4

 

8 10

1 2

2 3

5 6

7 5

4 6

3 6

6 7

2 5

2 4

4 3

样例输出

3

2

 

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <algorithm>#define N 1100int f[N]={0}, n, m, k;void init(){int i;for(i=1; i<=n; i++)f[i]=i;}int getf(int v){if(f[v]==v)return v;else{f[v]=getf(f[v]);return f[v];}}void merge(int v, int u){int t1, t2;t1=getf(v);t2=getf(u);if(t1 != t2){f[t2]=t1;}}int main(){int i, x, y, sum, t;scanf("%d", &t);while(t--){scanf("%d %d", &n, &m);init();for(i=1; i<=m;i++){scanf("%d %d", &x, &y);merge(x, y);}for(i=1, sum=0; i<= n; i++){if(f[i]==i)sum++;}printf("%d\n", sum);}return 0;}

0 0
原创粉丝点击