码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1598

时间:2020-05-05 00:22:07      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:amp   不能   tor   oid   排序   turn   min   ret   col   

按边上限速从小到大排序,枚举最小限速,每次从某个边开始把后面的边加入路径直到起点终点联通,更新最小值为最大限速减去开始本次枚举的边上的限速。

若不能联通,输出-1。

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 struct node{
 5     int from,to,w;
 6     bool operator < (const node &a){
 7         return w<a.w;
 8     }
 9 }a[1001];
10 int n,m,f[201],q,u,v,ans=1e9,j;
11 void ini(){
12     for (int i=1;i<=n;i++) f[i]=i;
13 }
14 
15 int getf(int u){
16     return f[u]==u?f[u]:f[u]=getf(f[u]);
17 }
18 
19 void merge(int u,int v){
20     f[getf(u)]=getf(v);
21 }
22 
23 void solve(){
24     while (cin>>n>>m){
25         for (int i=1;i<=m;i++) scanf("%d %d %d",&a[i].from,&a[i].to,&a[i].w);
26         sort(a+1,a+1+m);
27         cin>>q;
28         while (q--){
29             scanf("%d %d",&u,&v);
30             ans=1e9;
31             for (int i=1;i<=m;i++){
32                 ini();
33                 for (j=i;j<=m && getf(u)!=getf(v);j++) merge(a[j].from,a[j].to);
34                 if (getf(u)==getf(v)) ans=min(ans,a[j-1].w-a[i].w);
35             }
36             if (ans==1e9) cout<<-1<<endl;
37             else cout<<ans<<endl;
38         }
39     }
40 }
41 
42 int main()
43 {
44     solve();
45     return 0;
46 }

 

HDU1598

标签:amp   不能   tor   oid   排序   turn   min   ret   col   

原文地址:https://www.cnblogs.com/whiteli/p/12828998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!