【面试题 & 并查集】

题目描述

n个数,分别是1-n,现把他们分堆并给出两两关系例如2-5 1-5,给出关系的两个数必须在同一堆,问最大分堆数。

思路

建图dfs或者并查集。

代码

没有写,先贴一个模板上来。

// 1389.cpp : 定义控制台应用程序的入口点。
// 并查集,求每个集合中的元素个数
// 在合并时将子树中的结点数目加到根结点
 
#include "stdafx.h"
#include <iostream>
#include <cstdio>
 
#define MAX 100000+5
 
int father[MAX]; //父节点
int people[MAX]; //每个集合中的元素个数
int rank[MAX]; //秩
 
int find(int x) 
{
	if (x != father[x])
		father[x] = find(father[x]);
 
	return father[x];
}
 
//合并并返回合并后的祖先序号
void Union(int x, int y) 
{
	x = find(x);
	y = find(y);
 
	if (rank[x] > rank[y])
	{
		father[y] = x;
 
		//两者祖先相同时,实际没发生合并,只考虑祖先不同的情况
		if (x != y)
			people[x] += people[y];
	}
	else
	{
		father[x] = y;
		
		//两者祖先相同时,实际没发生合并,只考虑祖先不同的情况
		if (x != y)
			people[y] += people[x];
 
		if (rank[x] == rank[y]) //树高相同时让父节点的树高值加一
			rank[y] += 1;
	}
}
 
//计算集合的个数
int count_sets(int n)
{
	int cnt = 0;
	for (int i = 1; i <= n; i++)
		if (find(i) == i)
			cnt++;
 
	return cnt;
}
 
int main()
{
	int n, m;
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++)
	{
		father[i] = i;
		people[i] = 1;
		rank[i] = 0;
	}
 
	char cmd;
	int x, y;
	while (m--)
	{
		getchar();
		scanf("%c", &cmd);
		if (cmd == 'M')
		{
			scanf("%d %d", &x, &y);
			Union(x, y);
		}
		else if (cmd == 'Q')
		{
			scanf("%d", &x);
			printf("%d\n", people[find(x)]);
		}
	}
 
	printf("集合个数:%d\n", count_sets(n));
 
	system("pause");
	return 0;
}
 
发布了340 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/105667067