WEEK 6 D data center (CSP201812-4)

topic

Insert picture description here

Example Input

4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2

Output

4

Sample description

Insert picture description here

Ideas:

What this problem requires is a spanning tree for the given graph. The weight of the side with the largest weight of the spanning tree must be the smallest among all spanning trees in the graph, that is, to find the smallest bottleneck spanning tree of the graph.
According to the nature of the minimum spanning tree, the minimum spanning tree must be the bottleneck spanning tree, and the bottleneck spanning tree is not necessarily the minimum spanning tree. This problem can be transformed into finding the weight of the largest edge of the smallest spanning tree for a given graph structure.
Using the Kruskal algorithm, each time an edge is selected, its weight is compared with the maximum weight of the current record. If it is greater than the current maximum weight, the record is updated. When the n-1 sides are full, the weight value recorded at this time is the answer.

Code:

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 50005;
const int M = 100005;
int par[N];
int n,m, tot;

struct edge
{
	int u, v, w;
	bool operator<(const edge &e)const
	{
		return w < e.w;
	}
}es[M];

void init(int n)
{
	for (int i = 0; i <= n; i++)
		par[i] = i;
}
int find(int x)
{
	if (par[x] == x)
		return x;
	else
		return par[x] = find(par[x]);
}
bool unite(int x, int y)
{
	x = find(x), y = find(y);
	if (x == y)
		return false;
	par[x] = y;
	return true;
}

int kruskal()
{
	init(n);
	sort(es+1, es + m + 1);
	int cnt = 0, ans = 0;
	for(int i=1;i<=m;i++)
		if (unite(es[i].u, es[i].v))
		{
			ans = max(ans,es[i].w);
			if (++cnt == n-1)
				return ans;
		}
	return -1;
}


int main()
{
	scanf("%d%d%d", &n, &m, &tot);
	for (int i = 1; i <= m; i++)
		scanf("%d%d%d", &es[i].u, &es[i].v, &es[i].w);
	printf("%d\n", kruskal());
	return 0;
}

Published 32 original articles · praised 0 · visits 678

Guess you like

Origin blog.csdn.net/qq_43814559/article/details/105254372