B - How Many Tables (多少桌)
题目大致意思:
有n个人在一起吃饭,有些人互相认识。认识的人想坐在一起,不想跟陌生人坐。例如A认识B,B认识C,那么A、B、C会坐在一张桌子上。
给出认识的人,问需要多少张桌子
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.
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
2 5 3 1 2 2 3 4 5 5 1 2 5
Sample Output
2 4
#include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; int mp[1010][1010]; int pre[1010]; int n,m; void init()//初始化先一人一张桌子 { for(int i=1;i<=n;i++) { pre[i]=i; } } int find(int x)//查找认识的人 { return x==pre[x]?x:find(pre[x]); } void merge(int x,int y)//将他们合并为一桌 { int tx=find(x); int ty=find(y); if(tx!=ty) { pre[tx]=ty; } } int main() { int t; cin>>t; while(t--) { memset(mp,0,sizeof(mp)); cin>>n>>m; memset(pre,0,sizeof(pre)); init(); for(int i=1;i<=m;i++) { int x,y; cin>>x>>y; merge(x,y); } int ans=0; for(int i=1;i<=n;i++)//统计有多少个集合 { if(pre[i]==i) ans++; } cout<<ans<<endl; } }