【codevs 1001】舒适的路线

1001 舒适的路线 2006年
时间限制: 2 s
空间限制: 128000 KB
题目等级 : 钻石 Diamond
题解
题目描述 Description
Z小镇是一个景色宜人的地方,吸引来自各地的观光客来此旅游观光。
Z小镇附近共有
N ( 1 < N ≤ 500 ) 个景点(编号为1,2,3,…,N),这些景点被M(0 < M ≤ 5000)条道路连接着,所有道路都是双向的,两个景点之间可能有多条道路。也许是为了保护该地的旅游资源,Z小镇有个奇怪的规定,就是对于一条给定的公路Ri,任何在该公路上行驶的车辆速度必须为Vi。频繁的改变速度使得游客们很不舒服,因此大家从一个景点前往另一个景点的时候,都希望选择行使过程中最大速度和最小速度的比尽可能小的路线,也就是所谓最舒适的路线。

输入描述 Input Description
第一行包含两个正整数,N和M。
接下来的M行每行包含三个正整数:x,y和v(1≤x,y≤N,0 最后一行包含两个正整数s,t,表示想知道从景点s到景点t最大最小速度比最小的路径。s和t不可能相同。

输出描述 Output Description
如果景点s到景点t没有路径,输出“IMPOSSIBLE”。否则输出一个数,表示最小的速度比。如果需要,输出一个既约分数。

样例输入 Sample Input
样例1
4 2
1 2 1
3 4 2
1 4

样例2
3 3
1 2 10
1 2 5
2 3 8
1 3

样例3
3 2
1 2 2
2 3 4
1 3

样例输出 Sample Output
样例1
IMPOSSIBLE

样例2
5/4

样例3
2

数据范围及提示 Data Size & Hint
N(1 < N ≤ 500)

M(0 < M ≤ 5000)

Vi在int范围内

题目要求,在能到达的前提下,最大速度与最小速度的比值尽量小
也就是两条边速度尽可能接近

如何保证能到达?
利用并查集维护,如果起点终点不在一个集合内,则无法到达

于是就最小生成树了x
所以把边按照权值从小到大排序
从最小权值的边开始枚举,下一条边一定比它自身大
如果下一条边加入,可以连通,就加

然后对于所有选中的边,最大最小比一下就好了
记得gcd约分~
记得初始化~

以及,这个题好像也可以从大到小,思路大致一样
哪天有空试一下√

以下AC代码

#include 
#include 
#include 
#include 
using namespace std;
const int MAXN = 5005;
int n,m,tot = 0;
int f,t,v,s,e,r;
int fa[MAXN],rank[MAXN];

int gcd(int x,int y)
{
    if(y == 0)  return x;
    return gcd(y,x % y);
}

struct edge
{
    int f,t,v;
    bool operator < (const edge &b)const
    {
        return v < b.v;
    }
}l[MAXN];

/*bool cmp(edge a,edge b)
{
    return a.v < b.v;
}*/

struct rabbit
{
    int fz,fm;
    bool operator < (const rabbit &b)const
    {
        return fz * b.fm < b.fz * fm;
    }
}zt[505 * 505];

void init()
{
    for(int i = 1; i <= n; i ++)    fa[i] = i;
    memset(rank,0,sizeof(rank));
    return;
}

int find(int x)
{
    return x == fa[x] ? x : fa[x] = find(fa[x]);
}

bool same(int x,int y)
{
    return find(x) == find(y);
}

void merge(int x,int y)
{
    x = find(x),y = find(y);
    if(rank[x] < rank[y])   swap(x,y);
    fa[x] = y;
    if(rank[x] == rank[y])  rank[y] ++;
    return;
}

void work(int s,int t)
{
    tot = 0;
    sort(l + 1,l + m + 1);
    for(int i = 1; i <= m; i ++)
    {
        init();
        zt[tot].fm = l[i].v;
        for(int j = i; j <= m; j ++)
        {
            merge(l[j].f,l[j].t );
            zt[tot].fz = l[j].v;
            if(same(s,t))   break;
        }
        if(same(s,t))   tot ++;// s t
    }
    return;
}

int main()
{
    scanf("%d %d",&n,&m);
    for(int i = 1; i <= m; i ++)
        scanf("%d %d %d",&l[i].f,&l[i].t,&l[i].v);
    scanf("%d %d",&s,&e);   
    work(s,e);
    sort(zt,zt + tot);
    if(!tot)
    {
        puts("IMPOSSIBLE");
        return 0;
    }
    if(zt[0].fz % zt[0].fm == 0)
    {
        printf("%d\n",zt[0].fz / zt[0].fm);
        return 0;
    }
    while((r = gcd(zt[0].fm,zt[0].fz)) - 1)
        zt[0].fm /= r,zt[0].fz /= r;
    printf("%d/%d\n",zt[0].fz,zt[0].fm);
    return 0;
}

你可能感兴趣的:(===图论===,===基础===,模拟/枚举)