HDU1598 ——find the most comfortable road(並查集)

來源:互聯網
上載者:User

將邊按速度進行從小達到的排序,設i是最大速度的邊,通過枚舉比i小的邊 for(j=i;j>=0;j--)  如果找到起點和終點在同一個集合裡,更新min。

測試資料較小,枚舉不會逾時。

#include<iostream>#include<algorithm>#include<cstdio>using namespace std;#define maxn 400#define INF 100000001int father[maxn],rank[maxn],n;struct Len{int start;int end;int speed;}len[1015];bool cmp(Len a,Len b){return a.speed<b.speed;}void makeset(){int i;for(i=1;i<=n;i++){father[i]=i;rank[i]=0;}}int getfather(int v){    if (father[v]==v)      return v;    else    {        father[v]=getfather(father[v]);        return father[v];     }}void Union(int x,int y){int fx,fy;    fx=getfather(x);    fy=getfather(y);    if(fy!=fx)       father[fx]=fy;}bool same(int x,int y){   return getfather(x)==getfather(y);}void judge(int x ,int y) {int fx,fy;     fx = getfather(x);     fy = getfather(y);     if (rank[fx]>rank[fy])        father[fy] = fx;     else     {        father[fx] = fy;        if(rank[fx]==rank[fy])           ++rank[fy];     }}int main(){int m;int min;int i,j;while(scanf("%d%d",&n,&m)!=EOF){for(i=0;i<m;i++)scanf("%d%d%d",&len[i].start,&len[i].end,&len[i].speed);sort(len,len+m,cmp);int q,s,e;int k,f;scanf("%d",&q);for(k=0;k<q;k++){min=INF;scanf("%d%d",&s,&e);for(i=0;i<m;i++){makeset();for(j=i;j>=0;j--){Union(len[j].start,len[j].end);judge(len[j].start,len[j].end);if(same(s,e)){if(min>len[i].speed-len[j].speed)min=len[i].speed-len[j].speed;break;}}}if(min!=INF)printf("%d\n",min);elseprintf("-1\n");}}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.