HDU1598 find the most comfortable road (最小產生樹,並查集的應用)

來源:互聯網
上載者:User

題目串連:http://acm.hdu.edu.cn/showproblem.php?pid=1598

題目大意:就是說有一個很奇葩的星球,假設有n個城市和m條路,每條路有自己的最大速度。現在給你起點和終點,要你求出一條路線是的你從起點可以到達終點並且這條路線中的速度的最大值和最小值是最小的。

題目思路:該題用到最小產生樹的演算法,,使用克魯斯卡爾。。先將道路權值自小到大排序,再依次枚舉權值下限,每次枚舉一個下限時,初始化一次,然後Kruskal演算法直到起點和終點兩點被連通,記錄這一路的極值。接著迴圈枚舉下一個下限,即比前一個下限大一點的權值。直到 所有權值被枚舉完,此時極值中的最小值就得到了。

參考代碼:

#include<iostream>using namespace std;#include<algorithm>#define INF 100000000#define MAX 250int n,m;int parent[250];struct node{int u;int v;int w;}map[1005];bool cmp(node a,node b){return a.w<b.w;}void UFset(){int i;for(i=0;i<=n;i++)parent[i]=-1;}int Find(int x){int s;int t;for(s=x;parent[s]>0;s=parent[s]);while(s!=x){t=parent[x];parent[x]=s;x=t;}return s;}int Union(int R1,int R2){int r1=Find(R1),r2=Find(R2);int t=parent[r1]+parent[r2];if(r1==r2)return 0;if(parent[r1]>parent[r2]){parent[r1]=r2;parent[r2]=t;}else{parent[r2]=r1;parent[r1]=t;}return 1;}int main(){while(cin>>n>>m){int i;for(i=0;i<m;i++){cin>>map[i].u>>map[i].v>>map[i].w;}sort(map,map+m,cmp);int Q,s,e;cin>>Q;while(Q--){cin>>s>>e;int min=INF;for(i=0;i<m;i++){UFset();for(int j=i;j<m;j++){if(Union(map[j].u,map[j].v)==1){if(Find(s)==Find(e)){if(min>(map[j].w-map[i].w)){min=map[j].w-map[i].w;break;}}}}}if(min==INF)cout<<"-1"<<endl;elsecout<<min<<endl;}}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.