Q

来源:互联网 发布:港澳台app直播软件 编辑:程序博客网 时间:2024/04/27 17:07
XX星有许多城市,城市之间通过一种奇怪的高速公路SARS(Super Air Roam Structure---超级空中漫游结构)进行交流,每条SARS都对行驶在上面的Flycar限制了固定的Speed,同时XX星人对 Flycar的“舒适度”有特殊要求,即乘坐过程中最高速度与最低速度的差越小乘坐越舒服 ,(理解为SARS的限速要求,flycar必须瞬间提速/降速,痛苦呀 ),<br>但XX星人对时间却没那么多要求。要你找出一条城市间的最舒适的路径。(SARS是双向的)。<br>
 

Input
输入包括多个测试实例,每个实例包括:<br>第一行有2个正整数n (1<n<=200)和m (m<=1000),表示有N个城市和M条SARS。<br>接下来的行是三个正整数StartCity,EndCity,speed,表示从表面上看StartCity到EndCity,限速为speedSARS。speed<=1000000<br>然后是一个正整数Q(Q<11),表示寻路的个数。<br>接下来Q行每行有2个正整数Start,End, 表示寻路的起终点。
 

Output
每个寻路要求打印一行,仅输出一个非负整数表示最佳路线的舒适度最高速与最低速的差。如果起点和终点不能到达,那么输出-1。
 

Sample Input
4 41 2 22 3 41 4 13 4 221 31 2
 

Sample Output
1

0

思路:刚看到这个题求一条最舒服的路径还是个最短路问题,这几天写报告总结看了,图这部分前面刷题大多用了图的最短路径算法,并查集没用几次

于是想在这题试试,用并查集来连接道路,用贪心求最短。

代码:

#include<stdio.h>#include<algorithm>using namespace std;int set[1005];struct node{    int s;    int e;    int w;} a[1005];int cmp(node c,node d){    return c.w>d.w;}int find(int x){    int r=x;    while(r!=set[r])        r=set[r];    int i=x;    while(i!=r)    {        int j=set[i];        set[i]=r;        i=j;    }    return r;}int main(){    int n,m,k,x,y,c,d;    while(scanf("%d%d",&n,&m)!=EOF)    {        for(int i=0; i<m; i++)        {            scanf("%d%d%d",&a[i].s,&a[i].e,&a[i].w);        }        sort(a,a+m,cmp);        scanf("%d",&k);        for(int h=1; h<=k; h++)        {            int i,j;            scanf("%d%d",&x,&y);            int ans=9999999;            for(i=0; i<m; i++)            {                for(int l=1; l<=n; l++)                {                    set[l]=l;                }                for(j=i; j<m; j++)                {                    int fx=find(a[j].s);                    int fy=find(a[j].e);                    if(fx!=fy)                    {                        set[fx]=fy;                    }                    if(find(x)==find(y))                    {                        if(ans>a[i].w-a[j].w)                            ans=a[i].w-a[j].w;                           break;                    }                }                if(j==m)                    break;            }            if(ans==9999999)                printf("-1\n");            else                printf("%d\n",ans);        }    }    return 0;}

0 0