AC(kruskal万岁)

 •  1天前


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

ll n, m, sum = 0, p[1000], h[1000] = {0}, power;

struct edge {
	int u, v;
	int w;
	bool operator<(const edge &other)const {
		return w < other.w;
	}
} adj[1000];

ll find(ll x) {
	if (p[x] != x) {
		return p[x] = find(p[x]);
	}
	return x;
}

void unite(ll x, ll y) {
	ll rootx = find(x);
	ll rooty = find(y);
	if (rootx == rooty)
		return;
	if (h[rootx] == h[rooty]) {
		p[rootx] = rooty;
		h[rooty]++;
	} else {
		if (h[rootx] > h[rooty])
			p[rooty] = rootx;
		else
			p[rootx] = rooty;
	}
}

void kruskal(ll n, ll m) {
	sort(adj + 1, adj + m + 1);
	ll count = 0;
	for (ll i = 1; i <= m; i++) {
		if (count == n)
			return;
		if (find(adj[i].u) != find(adj[i].v)) {
			unite(adj[i].u, adj[i].v);
			sum += adj[i].w;
			count++;
		}
	}
}

int main() {
	cin >> n >> m;
	for (ll i = 1; i <= m; i++) {
		cin >> adj[i].u >> adj[i].v >> adj[i].w;
	}
	for (ll i = 1; i <= n; i++) {
		p[i] = i;
	}
	kruskal(n, m);
	cin >> power;
	cout << sum << " " << sum *power;
	return 0;
}

评论:

请先登录,才能进行评论