算法训练营|图论第7天 prim算法 kruskal算法

题目:prim算法

题目链接:

53. 寻宝(第七期模拟笔试) (kamacoder.com)

代码:

#include
#include
#include
using namespace std;
int main() {
	int v, e;
	int x, y, k;
	cin >> v >> e;
	vector>grid(v + 1, vector(v + 1, 10001));
	while (e--) {
		cin >> x >> y >> k;
		grid[x][y] = k;
		grid[y][x] = k;
	}
	vectorminEdges(v + 1, 10001);
	vectorIntree(v + 1, false);
	for (int i = 1; i < v; i++) {
		int cur = -1;
		int MinVal = INT_MAX;
		for (int j = 1; j <= v; j++) {
			if (!Intree[j] && minEdges[j] < MinVal) {
				cur = j;
				MinVal = minEdges[j];
			}
		}
		Intree[cur] = true;
		for (int j = 1; j <= v; j++) {
			if (!Intree[j] && grid[cur][j] < minEdges[j]) {
				minEdges[j] = grid[cur][j];
			}
		}
	}
	int result = 0;
	for (int i = 2; i <= v; i++) {
		result += minEdges[i];
	}
	cout << result << endl;
}

题目:kruskal算法

题目链接:

53. 寻宝(第七期模拟笔试) (kamacoder.com)

代码:

#include
#include
#include
using namespace std;

struct Edge {
	int l, r, val;
};
int n = 10001;
vectorfather(n, -1);
void init() {
	for (int i = 0; i < n; i++) {
		father[i] = i;
	}
}
int find(int u) {
	if (u == father[u]) return u;
	else {
		return father[u] = find(father[u]);
	}
}
void join(int u, int v) {
	u = find(u);
	v = find(v);
	if (u == v) return;
	father[v] = u;

}
static bool cmp(const Edge& a, const Edge& b) {
	return a.val < b.val;
}

int main() {
	int v, e;
	int x, y, k;
	cin >> v >> e;
	vectoredges;
	while (e--) {
		cin >> x >> y >> k;
		edges.push_back({ x,y,k });
	}
	sort(edges.begin(), edges.end(), cmp);
	vectorresult;
	init();
	int result_val = 0;
	for (Edge edge : edges) {
		int x = find(edge.l);
		int y = find(edge.r);
		if (x != y) {
			result.push_back(edge);
			result_val += edge.val;
			join(x, y);
		}
	}
	
	cout << result_val << endl;
}

你可能感兴趣的:(算法,图论,数据结构)