0
点赞
收藏
分享

微信扫一扫

P2820 局域网(kruskal)

pipu 2022-04-26 阅读 64
算法
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <unordered_map>
#include <cmath>
#include <map>
#include <cctype>
#include <cstdlib>
#include <deque>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000010;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))

int n, k;
struct node {
	int u, v, val;
};
node edge[MAXN];
int fa[MAXN];

inline void init() {
	for (int i = 1; i <= n; i++) {
		fa[i] = i;
	}
}

int find(int x) {
	if (x == fa[x]) {
		return x;
	}
	return fa[x] = find(fa[x]);
}

inline void unite(int x, int y) {
	x = find(x);
	y = find(y);
	fa[x] = y;
}

inline bool same(int x, int y) {
	return find(x) == find(y);
}

bool cmp(node a, node b) {
	return a.val < b.val;
}
int cnt;

inline void kruskal() {
	int ans = 0;
	for (int i = 1; i <= k; i++) {
		if (edge[i].val == 0)
			continue;
		if (!same(edge[i].u, edge[i].v)) {
			unite(edge[i].u, edge[i].v);
		} else {
			ans += edge[i].val;
		}
	}
	printf("%d", ans);
}

int main() {
	scanf("%d %d", &n, &k);
	init();
	for (int i = 1; i <= k; i++) {
		scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].val);
	}
	sort(edge + 1, edge + k + 1, cmp);
	kruskal();
	return 0;
}

举报

相关推荐

局域网

无线局域网

虚拟局域网

Vlan虚拟局域网

Nginx 局域网共享

小白局域网搭建

0 条评论