1. Title Description: Click to open the link
2. How to solve the problem: In essence, the Kruskal algorithm is used to generate MST. First, according to the Benquan value from small to large order, for a continuous edge set [L,r], if the n points are all connected, there must be a slender degree not exceeding w[r]-w[l] of the spanning tree. Therefore, can be small to large enumeration L, for each L, using the Kruskal algorithm to generate a minimum spanning tree, calculate the degree of thinness, with ans take the smallest. If the enumeration ends, ans remains the INF. So output-1. Here you can add a preprocessing: If m<n-1, then the direct output-1.
3. Code:
#define _crt_secure_no_warnings #include <iostream> #include <algorithm> #include <string> #include <sstream> #include <set> #include <vector> #include <stack> #include <map> #include < queue> #include <deque> #include <cstdlib> #include <cstdio> #include <cstring> #include < cmath> #include <ctime> #include <functional>using namespace std; #define N 5000+10#define INF 100000000int U[n], v[n], W[n];int r[n], P[n];int N, m;int find (int x) {return p[x] = = x = x:p[x] = find (P[x]);} int CMP (const int I, const int j) {return w[i] < w[j];} int Kruskal (int L) {int ans = -1;int r;for (int i = 1; I <= n; i++)//Initialize and check set p[i] = i;for (R = L; R < M; r++) {int e = R[r];int x = Find (U[e]), int y = find (V[e]), if (x! = y) {ans = max (ans, w[e]-w[r[l]]);p [x] = y;}} int fa = FIND (1), for (int i = 1; I <= n; i++)//Determine if n points are all connected if (FA! = Find (i)) return ans=inf;return ans; int main () {//freopen ("test.txt", "R", stdin), while (CIN >> N >> M && (n | | m)) {int ans = inf;for (int i = 0; i < m; i++) scanf ("%d%d%d", &u[i], &v[i], &w[i]); for (i NT i = 0; I < m; i++) R[i] = I;sort (r, R + M, CMP), if (M < n-1) printf (" -1\n"), else{for (int i = 0; i < M-n + 2; i++) ans = min (ans, Kruskal (i)); if (ans = = INF) printf (" -1\n"), Else printf ("%d\n", ans);}} return 0;}
Example 11-2 slim spanning tree UVa1395