犯罪團伙

問題描述:

警察抓到了n個罪犯,警察根據經驗知道他們屬於不同的犯罪團伙,卻不能判斷有多少個團伙,但通過警察的審訊,知道其中一些罪犯之間互相認識,已知同一犯罪團伙的成員之間直接或者間接認識,有可能一個犯罪團伙只有一個人。請你根據已知罪犯之間的關係,確定犯罪團伙的數量。已知罪犯的編號從1到n。


輸入:

第一行:n(n<10000,罪犯數量)

第二行:m(m<100000,關係數量)

輸出:

一個整數,犯罪團伙的數量。


採用並查集來解決。

#include <stdio.h>

#define _MAX_LIST_SIZE_ 10001

int father[_MAX_LIST_SIZE_];
int list_size;

void init();
int find_set(int i);
void union_set(int x, int y);

int main(){
	init();
	int relation_number;
	scanf("%d", &relation_number);
	while(relation_number--){
		int x, y;
		scanf("%d%d",&x, &y);
		union_set(x, y);
	}
	int sum = 0;
	int check_loop;
	for(check_loop = 1; check_loop <= list_size; check_loop++) if(check_loop == father[check_loop]) sum++;
	printf("%d\n", sum);
	return 0;
}

void init(){
	scanf("%d", &list_size);
	int input_loop;
	for(input_loop = 1; input_loop <= list_size; input_loop++) father[input_loop] = input_loop;
}

int find_set(int i){
	int grand_father = i;
	while(grand_father != father[grand_father]) grand_father = father[grand_father];
	return grand_father;
}

void union_set(int x, int y){
	int a = find_set(x);
	int b = find_set(y);
	if(a < b) father[b] = a;
	else if( b < a) father[a] = b;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章