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< N<=500,1<=x,y<=N,0 < v<30000, 0 < M<=5000
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
题解
我们可以枚举最小的边,这样我们只需要保证最大边最小即可。显然最小瓶颈生成树即最小生成树。
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn=510;
const int maxm=5010;
const int INF=31000;
int fa[maxn];
struct edge
{
int u,v,w;
}e[maxm];
vector <edge> g[maxn];
bool cmp(edge a,edge b)
{
return a.w<b.w;
}
int find(int x)
{
return fa[x]==x?x:fa[x]=find(fa[x]);
}
int n,m,s,tt;
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
int dfs(int x,int en,int a,int father)
{
if(x==en)return a;
int ans=0;
for(int i=0;i<g[x].size();i++)
{
edge &u=g[x][i];
if(u.v==father)continue;
int t=dfs(u.v,en,u.w>a?u.w:a,x);
ans=ans>t?ans:t;
}
return ans;
}
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,&tt);
sort(e+1,e+m+1,cmp);
int have=0,ans1,ans2;
double minans=INF;
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
g[j].clear();
fa[j]=j;
}
int tot=0;
for(int j=1;j<=m;j++)
{
int t1=find(e[j].u),t2=find(e[j].v);
if(t1!=t2&&e[j].w>=e[i].w)
{
tot++;
fa[t2]=t1;
g[t2].push_back((edge){t2,t1,e[j].w});
g[t1].push_back((edge){t1,t2,e[j].w});
if(tot==n-1)break;
}
}
if(find(s)==find(tt))
{
have=1;
int t=dfs(s,tt,0,0);
if(t*1.0/e[i].w<minans)
{
minans=t*1.0/e[i].w;
ans1=t;
ans2=e[i].w;
}
}
}
if(!have)
{
printf("IMPOSSIBLE");
return 0;
}
int t=gcd(ans1,ans2);
ans1/=t;
ans2/=t;
if(ans2==1)
{
printf("%d",ans1);
}
else
{
printf("%d/%d",ans1,ans2);
}
return 0;
}