欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C語(yǔ)言題目:有多少?gòu)堊雷?-并查集

 更新時(shí)間:2021年09月07日 11:21:20   作者:hnjzsyjyj  
并查集是一種用于管理分組的數(shù)據(jù)結(jié)構(gòu)。它具備兩個(gè)操作:(1)查詢?cè)豠和元素b是否為同一組 (2) 將元素a和b合并為同一組,需要的朋友可以參考下

【Problem Description】問(wèn)題描述

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.

今天是伊格納修斯的生日。他邀請(qǐng)了很多朋友。現(xiàn)在是吃晚飯的時(shí)間了。伊格納修斯想知道他至少需要多少?gòu)堊雷?。你必須注意,并不是所有的朋友都互相認(rèn)識(shí),而且所有的朋友都不想和陌生人呆在一起。
這個(gè)問(wèn)題的一個(gè)重要規(guī)則是,如果我告訴你A認(rèn)識(shí)B,B認(rèn)識(shí)C,這意味著A,B,C相互認(rèn)識(shí),所以他們可以呆在一張桌子上。
例如:如果我告訴你A知道B,B知道C,D知道E,那么A,B,C可以呆在一張桌子上,而D,E必須呆在另一張桌子上。所以伊格納修斯至少需要兩張桌子。

【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.

 輸入以整數(shù)T(1<=T<=25)開(kāi)始,表示測(cè)試用例的數(shù)量。然后,T測(cè)試用例隨之出現(xiàn)。每個(gè)測(cè)試用例從兩個(gè)整數(shù)N和M開(kāi)始(1<=N,M<=1000)。N表示朋友的數(shù)量,朋友標(biāo)記為從1到N。然后M行跟隨。每行由兩個(gè)整數(shù)A和B(A=B) 意思是朋友A和朋友B彼此認(rèn)識(shí)。兩個(gè)案例之間將有一個(gè)空白行。

【Output】輸出

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

對(duì)于每個(gè)測(cè)試用例,只需輸出Ignatius至少需要多少個(gè)表。不要打印任何空白。 

【Sample Input】樣本輸入

2
5 3
1 2
2 3
4 5

5 1
2 5

【Sample Output】樣本輸出

2
4

【Code】代碼

#include <iostream>
using namespace std; 
const int maxn=1005;
int pre[maxn]; 
int find(int x) {
	if(x!=pre[x]) pre[x]=find(pre[x]);
	return pre[x];
} 
void merge(int x,int y) {
	if(find(x)!=find(y)) pre[find(x)]=find(y);
} 
int main() {
	int T,N,M;
	int p,q;
	scanf("%d",&T);
	while(T--) {
		int ans=0;
		scanf("%d%d",&N,&M); 
		for(int i=1; i<=N; i++) pre[i]=i; 
		for(int i=1; i<=M; i++) {
			scanf("%d%d",&p,&q);
			merge(p,q);
		} 
		for(int i=1; i<=N; i++) {
			if(find(i)==i) ans++;
		} 
		printf("%d\n",ans);
	} 
	return 0;
}
 
 

/*
in:
2
5 3
1 2
2 3
4 5
5 1
2 5
out:
2
4
*/

總結(jié)

本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

最新評(píng)論