ACM--steps--dyx--5.1.4--find the most comfortable road

find the most comfortable road

Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 193 Accepted Submission(s): 94
 
Problem Description
XX星有許多城市,城市之間通過一種奇怪的高速公路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 4
1 2 2
2 3 4
1 4 1
3 4 2
2
1 3
1 2
 
Sample Output
1
0
 
Author
ailyanlu
 
Source
HDU 2007-Spring Programming Contest - Warm Up (1)
 
Recommend
8600

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int n,m;//表示所在城市數和共有m條道路;
const int Max=1009;
int dyx[209];//表示每一個節點所在的上一個節點;
const int INF=9999999;
int min(int a,int b)
{
    if(a>b)
    return b;
    else
    return a;
}
class Node
{
    public:
    int s,e,spe;//分別表示起點,終點,速度;
}wyx[Max];
//查詢根節點;
bool cmp(Node a,Node b)
{
    //將速度以升序進行排列;
    return a.spe<b.spe;
}
int find(int x)
{
    int r=x;
    while(dyx[r]!=r)
    {
        r=dyx[r];
    }
    return r;
}
//初始化;
void init()
{
    for(int i=1;i<=n;i++)
    {
        dyx[i]=i;
    }
}
//合併;
void mix(int a,int b)
{
    int RootA=find(a);
    int RootB=find(b);
    if(RootA!=RootB)
    {
        dyx[RootA]=RootB;
    }
}
int main()
{
    while(cin>>n>>m)
    {
        for(int i=0;i<m;i++)
        {
            cin>>wyx[i].s>>wyx[i].e>>wyx[i].spe;
        }
        sort(wyx,wyx+m,cmp);
        int T;
        cin>>T;
        while(T--)
        {
            int ans=INF;
            int St,Ed;
            cin>>St>>Ed;
            //進行枚舉所有的值;
            for(int i=0;i<m;i++)
            {
                //進行每一次的搜索前要先進行初始化;
                init();
                //遍歷所有的情況,從當前的i值爲起始點;
                for(int j=i;j<m;j++)
                {
                    //將當前起始點與終點合併;
                    mix(wyx[j].s,wyx[j].e);
                    //當起點和終點連通起來的時候;'
                    if(find(St)==find(Ed))
                    {
                        //sort排序保證當前的值爲最優解;
                       ans=min(ans,wyx[j].spe-wyx[i].spe);
                       break;
                    }
                }
            }
            if(ans==INF)
            cout<<-1<<endl;
            else
            cout<<ans<<endl;
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章