笔试刷题并查集专题

并查集专题

  • 合并集合

合并集合

#include 

using namespace std;

const int N = 1e5 + 10;
int p[N];

int find(int a)
{
	if (p[a] != a) p[a] = find(p[a]);
	return p[a];
}

int main()
{
	int n, m;
	cin >> n >> m;

	for (int i = 1; i <= n; i++) p[i] = i;

	int a, b;
	char op[2];
	while (m--)
	{
		cin >> op[0] >> a >> b;
		if (op[0] == 'M') p[find(a)] = find(b);
		else {
			if (find(a) == find(b)) puts("Yes");
			else puts("No");
		}
	}
	return 0;
}
#include
#include

#define VERTICES 6

using namespace std;

void initialise(vector& parent) {
	int i;
	for (i = 0; i < VERTICES; i++) {
		parent[i] = -1;
	}
}

int find_root(int x, vector& parent) {
	int x_root = x;
	while (parent[x_root]!=-1) {
		x_root = parent[x_root];
	}
	return x_root;
}

int union_vertices(int x, int y, vector& parent) {
	int x_root = find_root(x, parent);
	int y_root = find_root(y, parent);
	if (x_root == y_root) {
		return 0;
	}
	else {
		parent[x_root] = y_root;
		return 1;
	}
}
int main() {
	vector parent(VERTICES, 0);
	vector> edges = { {0,1},{1,2},{1,3},{2,4},{3,4},{2,5} };
	initialise(parent);
	for (int i = 0; i < 6; i++) {
		int x = edges[i][0];
		int y = edges[i][1];
		if (union_vertices(x, y, parent) == 0) {
			cout << "Cycle detected!";
			system("pause");
			return 0;
		}
	}
	cout << "No Cycle detected!";
	system("pause");
	return 0;
}

你可能感兴趣的:(算法笔试,算法与数据结构,并查集)