代码包熟的,不保熟你来找我

躺平摆烂学废卷赢都不会的rj  •  1个月前


include <bits/stdc++.h>

define INF 0x3f3f3f3f

using namespace std;

struct edge {

int form, to, w;

} e[102]; int fa[102]; int n, m, cnt = 1; int ans = INF;

bool cmp(edge a, edge b) {

return a.w < b.w;

}

void init() {

for (int i = 0; i < 102; i++)
	fa[i] = i;

}

void addedge(int u, int v, int w) {

e[cnt].form = u;
e[cnt].to = v;
e[cnt].w = w;
cnt++;

}

int find(int x) {

if (x != fa[x])
	fa[x] = find(fa[x]);
return fa[x];

}

void Union(int x, int y) {

x = find(x);
y = find(y);
if (x != y)
	fa[x] = y;

}

void kruskal() {

int k = 0;
sort(e + 1, e + 1 + m, cmp);
for (int i = 1; i <= m; i++) {
	init();//hahanibeipianle
	k = 0;
	for (int j = i; j <= m; j++) {
		if (find(e[j].form) != find(e[j].to)) {
			Union(e[j].form, e[j].to);
			k++;
		}
		if (k == n - 1) {
			ans = min(ans, e[j].w - e[i].w);
			break;
		}
	}
}

}

int main() {

init();
cin >> n >> m;
for (int i = 0; i < m; i++) {
	int u, v, w;
	cin >> u >> v >> w;
	addedge(u, v, w);
}
kruskal();
cout << ans;
return 0;

}


评论:

请先登录,才能进行评论