hdoj 1598 find the most comfortable road 【並查集】+【暴力枚舉】,hdoj1598

來源:互聯網
上載者:User

hdoj 1598 find the most comfortable road 【並查集】+【暴力枚舉】,hdoj1598

find the most comfortable roadTime Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4022    Accepted Submission(s): 1732

Problem DescriptionXX星有許多城市,城市之間通過一種奇怪的高速公路SARS(Super Air Roam Structure---超級空中漫遊結構)進行交流,每條SARS都對行駛在上面的Flycar限制了固定的Speed,同時XX星人對 Flycar的“舒適度”有特殊要求,即乘坐過程中最高速度與最低速度的差越小乘坐越舒服 ,(理解為SARS的限速要求,flycar必須瞬間提速/降速,痛苦呀 ),
但XX星人對時間卻沒那麼多要求。要你找出一條城市間的最舒適的路徑。(SARS是雙向的)。
 
Input輸入包括多個測試執行個體,每個執行個體包括:
第一行有2個正整數n (1<n<=200)和m (m<=1000),表示有N個城市和M條SARS。
接下來的行是三個正整數StartCity,EndCity,speed,表示從表面上看StartCity到EndCity,限速為speedSARS。speed<=1000000
然後是一個正整數Q(Q<11),表示尋路的個數。
接下來Q行每行有2個正整數Start,End, 表示尋路的起終點。 
Output每個尋路要求列印一行,僅輸出一個非負整數表示最佳路線的舒適度最高速與最低速的差。如果起點和終點不能到達,那麼輸出-1。 
Sample Input
4 41 2 22 3 41 4 13 4 221 31 2
 
Sample Output
10

分析:先按照速度從小到大排序,然後從當前i開始到n建立並查集,直到初始和目的形成串連,然後與ans比較

代碼:

/*hdoj 1598*/ #include <stdio.h>#include <string.h>#include <algorithm>#define M 1005#define INF 0x3f3f3f3fusing namespace std;struct node{    int from, to, sp;}s[M];int fat[M], n, m;int f(int x){    if(fat[x] != x) fat[x] = f(fat[x]);    return fat[x];}int cmp(node a, node b){    return a.sp<b.sp;    }int main(){    int i, a, b, c, j, q;    while(scanf("%d%d", &n, &m) == 2){        for(i = 0; i < m; i ++)            scanf("%d%d%d", &s[i].from, &s[i].to, &s[i].sp);        sort(s, s+m, cmp);                scanf("%d", &q);        while(q --){            int ans = INF;            scanf("%d%d", &a, &b);            for(i = 0; i < m; i ++){                for(j = 1; j <= n; j ++) fat[j] = j;                for(j = i; j < m; j ++){                    int x = f(s[j].from);                    int y = f(s[j].to);                    if(x!=y) fat[x] = y;                    if(f(a) == f(b)){                        ans = min(ans, s[j].sp-s[i].sp); break;                    }                }            }            if(ans == INF) printf("-1\n");            else printf("%d\n", ans);        }    }    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.