HDOJ1232畅通工程(纯正的并查集)

Xredman posted @ Mar 15, 2010 10:13:53 PM in Algorithm with tags HDU 并查集 , 1574 阅读

        有n个相互不连通的集合(相互连通的城市归为一个集合),就需要构建n-1条新道路。此题为典型的并查集。用第一种并查集实现。

//2190468 2010-03-16 08:17:26 Accepted 1232 62MS 288K 914 B C++ 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <set>
using namespace std;

const int N = 1004;
int UFSet[N];

int n;//并查集中元素个数
int m;

void init()
{
	for(int i = 1; i <= n; i++)
		UFSet[i] = i;
}

int find(int x)
{//查找x元素所在集合号,时间复杂度为O(1)
	return UFSet[x];
}

void merge(int x, int y)
{//合并元素x和元素y,时间复杂度为O(N)
	int a, b;
	a = min(UFSet[x], UFSet[y]);
	b = max(UFSet[x], UFSet[y]);
	for(int k = 1; k <= n; k++)
		if(UFSet[k] == b)
			UFSet[k] = a;
}

int main()
{
	int i;
	int citya, cityb;
	set<int> S;
	while(scanf("%d", &n) && n)
	{
		scanf("%d", &m);
		init();
		for(i = 0; i < m; i++)
		{
			scanf("%d %d", &citya, &cityb);
			merge(citya, cityb);
		}
		S.clear();
		for(i = 1; i <= n; i++)
			S.insert(find(i));
		printf("%d\n", S.size() - 1);
	}
	return 0;
}






HBSE 7th Question P 说:
Sep 29, 2023 06:44:57 PM

Haryana 7th Important Question Paper 2024 for Hindi, English, Mathematics, Science, Social Science, These Practice Paper Importance for Those will attain the Upcoming Final Exam 2024. The best way to Download your Haryana Exam Preparation level is by Previous Question Paper.These Haryana Model Paper 2024 are Provided by the Board for the better Exam Preparation of Students and are HBSE 7th Question Paper 2024 also available in the official website, This Exam Paper Prepare by Senior Exports of Haryana Education Board,Haryana Model Paper 2024 help the Students to get a Clear idea about the Final Exam 2024.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter