HDU 1598 find the most comfortable road(最小生成树之Kruskal)

2023-06-05,,

题目链接: 传送门

find the most comfortable road

Time Limit: 1000MS     Memory Limit: 32768 K

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 Iutput

4 4
1 2 2
2 3 4
1 4 1
3 4 2
2
1 3
1 2

Sample Output

1
0

解题思路:

贪心的Kruskal最小生成树思路,首先将边的权值(亦即题目所说的speed)按从小到大排序,然后从小到大枚举,寻找到目标起点与目标终点所经路径的权值最大与最小的差,更新最小值即可。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 205;
const int maxm = 1005;
struct Edge{
    int u,v,w;
};
struct Edge edge[maxm];
int N,M,father[maxn],rk[maxn];

bool cmp(Edge x,Edge y)
{
    return x.w < y.w;
}

void init()
{
    memset(father,0,sizeof(father));
    memset(rk,0,sizeof(rk));
    for (int i = 0; i <= N; i++)
    {
        father[i] = i;
    }
}

int find(int x)
{
    int r = x;
    while (father[r] != r)
    {
        r = father[r];
    }
    int i = x,j;
    while (i != r)
    {
        j = father[i];
        father[i] = r;
        i = j;
    }
    return r;
}

void unite(int x,int y)
{
    int fx,fy;
    fx = find(x);
    fy = find(y);
    if (fx == fy)   return;
    if (rk[fx] < rk[fy])
    {
        father[fx] = fy;
    }
    else
    {
        father[fy] = fx;
        if (rk[x] == rk[y])
        {
            rk[x]++;
        }
    }

}

int main()
{
    while (~scanf("%d%d",&N,&M))
    {
        int u,v,w,Q,st,ed,res;
        for (int i = 0;i < M;i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            edge[i].u = u;
            edge[i].v = v;
            edge[i].w = w;
        }
        sort(edge,edge+M,cmp);
        scanf("%d",&Q);
        while (Q--)
        {
            res = INF;
            scanf("%d%d",&st,&ed);
            for (int i = 0;i < M;i++)
            {
                init();
                for (int j = i;j < M;j++)
                {
                    unite(edge[j].u,edge[j].v);
                    if (find(st) == find(ed))
                    {
                        res = min(res,edge[j].w - edge[i].w);
                        break;
                    }
                }
            }
            printf("%d\n",res == INF?-1:res);
        }
    }
    return 0;
}

HDU 1598 find the most comfortable road(最小生成树之Kruskal)的相关教程结束。

《HDU 1598 find the most comfortable road(最小生成树之Kruskal).doc》

下载本文的Word格式文档,以方便收藏与打印。