hdu-1598 find the most comfortable road---kruskal+enum lower bound

Topic link:

http://acm.hdu.edu.cn/showproblem.php?pid=1598

Topic meaning:

There are many cities in XX star, and the cities communicate through a strange highway SARS (Super Air Roam Structure---Super Air Roam Structure). Each SARS restricts a fixed Speed ​​to the Flycar driving on it. XX stars have special requirements for Flycar's "comfort", that is, the smaller the difference between the maximum speed and the minimum speed during the ride, the more comfortable the ride is. ,
but XX stars do not have so many requirements for time. To find the most comfortable path between cities. (SARS goes both ways).

Problem solving ideas:

Sort the edges, enumerate the lower bounds from small to large, add each edge in turn, and know that the target point is just connected, then it is exactly the maximum-minimum value. answer minimum

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 1000 + 10;
 4 const int INF = 0x3f3f3f3f;
 5 struct node
 6 {
 7     int u, v, w;
 8     bool operator <(const node & a)const
 9     {
10         return w < a.w;
11     }
12 }a[maxn];
13 int p[maxn];
14 void init()
15 {
16     for(int i = 0; i < maxn; i++)p[i] = i;
17 }
18 int Find(int x)
19 {
20     return x == p[x] ? x : p[x] = Find(p[x]);
21 }
22 void Union(int x, int y)
23 {
24     p[Find(x)] = Find(y);
25 }
26 int main()
27 {
28     int n, m;
29     while(cin >> n >> m)
30     {
31         for(int i = 0; i < m; i++)
32         {
33             cin >> a[i].u >> a[i].v >> a[i].w;
34         }
35         sort(a, a + m);
36         int t, u, v;
37         cin >> t;
38         while(t--)
39         {
40             cin >> u >> v;
41             int ans = INF;
42             for(int start = 0; start < m; start++)
43             {
44                 init();
45                 for(int end = start; end < m; end++)
46                 {
47                     Union(a[end].u, a[end].v);
48                     if(Find(u) == Find(v))
49                     {
50                         ans = min(ans, a[end].w - a[start].w);
51                     }
52                 }
53             }
54             if(ans < INF)cout<<ans<<endl;
55             else cout<<"-1"<<endl;
56         }
57     }
58     return 0;
59 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324634750&siteId=291194637