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不可能相同。
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
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
IMPOSSIBLE
【样例输出2】
5/4
【样例输出3】
2
HINT
【数据范围】
1< N < = 500
1 < = x, y < = N,0 < v < 30000,x ≠ y
0 < M < =5000
Source
枚举最大边,然后求最小生成树,记录最优值。
然后,就没了。
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
inline int read()
{
int x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-') f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9')
{
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
struct Edge
{
int u, v, w;
}a[5010];
int n, m, f[510];
int gcd(int a, int b)
{
if(a > b) swap(a, b);
while(a)
{
int c = a;
a = b % a;
b = c;
}
return b;
}
int find(int x)
{
if(f[x] == x) return f[x];
else return f[x] = find(f[x]);
}
int cmp(Edge a, Edge b)
{
return a.w < b.w;
}
int main()
{
n = read();
m = read();
for(int i = 1; i <= m; i ++)
a[i].u = read(), a[i].v = read(), a[i].w = read();
sort(a + 1, a + m + 1, cmp);
int s, t, start = 1, ansmx = 1, ansmn = 0;
s = read();
t = read();
while(start <= m)
{
int mn, mx, x;
mn = mx = -1;
for(int i = 1; i <= n; i ++)
f[i] = i;
for(x = start; x <= m; x ++)
{
int u = find(a[x].u);
int v = find(a[x].v);
f[u] = v;
if(find(s) == find(t))
{
mx = a[x].w;
break;
}
}
if(mx == -1)
{
if(!ansmn) {printf("IMPOSSIBLE\n"); return 0;}
else break;
}
for(int i = 1; i <= n; i ++)
f[i] = i;
for(; x > 0; x --)
{
int u = find(a[x].u);
int v = find(a[x].v);
f[u] = v;
if(find(s) == find(t))
{
mn = a[x].w;
break;
}
}
start = x + 1;
if(mn == -1)
{
if(!ansmn) {printf("IMPOSSIBLE\n"); return 0;}
else break;
}
int r = gcd(mx, mn);
mx /= r;
mn /= r;
if(ansmx * mn > ansmn * mx)
{
ansmn = mn;
ansmx = mx;
}
}
if(ansmn == 1) printf("%d\n", ansmx);
else printf("%d/%d\n", ansmx, ansmn);
return 0;
}