2021-02-25 Minimum spanning tree template-krusal algorithm

Summary:

Minimum spanning tree algorithm template-krusal algorithm


Brief description of the topic:

Luogu P3366 minimum spanning tree template


Analysis of Algorithms:

The krusal algorithm mainly uses the idea of ​​greed. Now all edges are sorted according to their weights, and then an edge with the smallest weight is added each time. Since the graph is simplified to a trivial graph containing only n points at the beginning, the newly added edge satisfies the need to add no loop.
Initially, there are n points, and every time an edge is added, the two points will be connected. This feature just satisfies the feature of union search. Therefore, krusal's code implementation can use the union search algorithm.


Code and detailed comments:

#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <numeric>
#define INF 10000000
#pragma warning(disable:4996)
using namespace std;

struct edge {
    
    
	int u; 
	int v;
	int w;
};

bool comp(edge& e1, edge& e2)
{
    
    
	return e1.w < e2.w;
}

class UnionFind {
    
    
public:
	int count; //种类数
	vector<int> root; //保存每一个节点的根节点
	UnionFind(int _count = 1) :count(_count)
	{
    
    
		root.resize(_count + 1);
		for (int i = 1; i <= _count; ++i)
			root[i] = i;
	}

	//路径压缩
	int find(int x) {
    
    
		return root[x] == x ? root[x] : root[x] = find(root[x]);
	}

	void Union(int x,int y) {
    
    
		int rootx = find(x);
		int rooty = find(y);
		if (rootx != rooty)
			root[y] = rootx;
	}
};

class Solution {
    
    
public:
	int cnt = 0;
	vector<edge> e;
	int n, m;
	int count = 0;
	int ans = 0;
	inline void add_edge(int u, int v, int w) {
    
    
		cnt++;
		e[cnt].u = u;
		e[cnt].v = v;
		e[cnt].w = w;
	}

	void krusal() {
    
    
		cin >> n >> m;
		e.resize(m + 1);

		for (int i = 0; i < m; ++i)
		{
    
    
			int u, v, w;
			cin >> u >> v >> w;
			add_edge(u, v, w);
		}
		sort(e.begin(), e.end(), comp);
		UnionFind un(n);
		for (int i = 1; i <= m; ++i)
		{
    
    
			int u = un.find(e[i].u);
			int v = un.find(e[i].v);
			if (u == v)
				continue;
			ans += e[i].w;
			count++;
			un.Union(u, v);
		}
		if (count == n - 1)
			cout << ans << endl;
		else
			cout << "orz" << endl;
	}

};

int main() {
    
    

	//freopen("in.txt", "r", stdin);
	Solution s;
	s.krusal();
	return 0;

}

Guess you like

Origin blog.csdn.net/sddxszl/article/details/114055589