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<algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <string> #include <cmath> #include <queue> #include <stack> #include <set> #include <map> using namespace std; #define P(a,b,c) make_pair(a,make_pair(b,c)) #define rep(i,a,n) for (int i=a;i<=n;i++) #define per(i,a,n) for (int i=n;i>=a;i--) #define CLR(vis) memset(vis,0,sizeof(vis)) #define MST(vis,pos) memset(vis,pos,sizeof(vis)) #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second #define SZ(x) ((int)(x).size()) typedef pair<int,pair<int,int> >pii; typedef long long ll; const ll mod = 1000000007; ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; } const int maxn = 3e4+5; int pre[maxn]; int rankk[maxn]; int find(int x){ return pre[x]==x?x:pre[x]=find(pre[x]); } void unionn(int a,int b){ a = find(a); b = find(b); if(a==b)return; else{ if(rankk[a]<rankk[b]) pre[a]=b; else { pre[b] = a; if(rankk[a] == rankk[b]) rankk[a]++; } } } void init(int n){ rep(i,1,n){ rankk[i]=1; pre[i]=i; } } set<int>s; int main(){ int n,m,t; scanf("%d", &t); while(t--){ s.clear(); scanf("%d%d", &n,&m); init(n); while(m--){ int u,v; scanf("%d%d",&u,&v); unionn(u,v); } int cnt = 0; rep(i,1,n){ if(!s.count(find(i))){ s.insert(find(i)); cnt++; } } cout<<cnt<<endl; } return 0; }