Description
给你一个无向图,N(N<=500)个顶点, M(M<=5000)条边,每条边有一个权值Vi(Vi<30000)。给你两个顶点S和T,求
一条路径,使得路径上最大边和最小边的比值最小。如果S和T之间没有路径,输出”IMPOSSIBLE”,否则输出这个
比值,如果需要,表示成一个既约分数。 备注: 两个顶点之间可能有多条路径。
Input
第一行包含两个正整数,N和M。下来的M行每行包含三个正整数:x,y和v。表示景点x到景点y之间有一条双向公路
,车辆必须以速度v在该公路上行驶。最后一行包含两个正整数s,t,表示想知道从景点s到景点t最大最小速度比
最小的路径。s和t不可能相同。
1
Output
如果景点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
题解
这道题目非常巧妙!需要for一遍所有的边,以这条边为最小边跑最小生成树。但是题目只需要s和t连通就行了,所以停在s和t联通的的那条边(也就是s到t最大的边)停止就可以了。但是这里有一个小小的Tips~!为什么可以直接用当前固定的最小边和s到t最大的边更新答案?原因是如果用了路径之外的小于路径之内的边来更新答案,迟早会被路径之内的答案又更新掉;而路径之外大于路径的边,就不会使s和t联通了。
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 50010;
struct Edge {
int u, v, w;
} e[N];
int n, m, s, t, fa[N], tot, num = 0, head[N], a1 = -1, a2;
bool cmp(const Edge &a, const Edge &b) {
return a.w < b.w;
}
double ans = 987654321.0;
int gcd(int a, int b) {
return b ? gcd(b, a % b) : a;
}
void check(int a, int b) {
double x = (double) a / (double) b;
if(x < ans) {
ans = x; int y;
if(a / b * b == a) a1 = a / b, a2 = -1;
else y = gcd(a, b), a1 = a / y, a2 = b / y;
}
}
int find(int x) {
if(x == fa[x]) return x;
return fa[x] = find(fa[x]);
}
void krusal() {
for(int i = 1; i <= m; i ++) {
for(int j = 1; j <= n; j ++) fa[j] = j;
for(int j = i; j <= m; j ++) {
int fx = find(e[j].u), fy = find(e[j].v);
if(fx == fy) continue; fa[fy] = fx;
int x = find(s), y = find(t);
if(x == y) {
check(e[j].w, e[i].w);
break;
}
}
if(find(s) != find(t)) return ;
}
}
int main() {
scanf("%d %d", &n, &m);
for(int i = 1; i <= m; i ++)
scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w);
scanf("%d %d", &s, &t);
sort(e + 1, e + m + 1, cmp); krusal();
if(a1 == -1) printf("IMPOSSIBLE\n");
else if(a2 == -1) printf("%d", a1);
else printf("%d/%d\n", a1, a2);
return 0;
}