并查集的思想。
枚举最短边。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
int gcd(int x,int y)
{
if (y>x) return gcd(y,x);
if (!y) return x;
return gcd(y,x%y);
}
struct node
{
int v,u,val;
}edge[50000];
int ans1,tmp,ans2;
int n,e;
int father[50000];
bool cmp(node aa,node bb)
{
return aa.val<bb.val;
}
int getfather(int x)
{
if(father[x]==x) return x;
father[x]=getfather(father[x]);
return father[x];
}
int main()
{
int st,ed;
scanf("%d%d",&n,&e);
for(int i=1;i<=e;i++)
{
scanf("%d%d%d",&edge[i].v,&edge[i].u,&edge[i].val);
}
scanf("%d%d",&st,&ed);
sort(edge+1,edge+1+e,cmp);
for(int i=1;i<=e;i++)
{
int j;
for(j=1;j<=n;j++)
father[j]=j;
for(j=i;j<=e;j++)
{
int r1=getfather(edge[j].v);
int r2=getfather(edge[j].u);
if(r1!=r2)
{
father[r1]=r2;
if (getfather(st)==getfather(ed)) break;//核心,st和ed相同就停止。
}
}
int r1=getfather(st);
int r2=getfather(ed);
if ((i==1)&&(r1!=r2))
{
printf("IMPOSSIBLE\n");
return 0;
}
if (r1!=r2) break;
if (ans1*edge[i].val>=ans2*edge[j].val)
ans1=edge[j].val,ans2=edge[i].val;//如果用double会有精度误差
}
int x=gcd(ans1,ans2);
if (x==ans2) printf("%d\n",ans1/ans2); else printf("%d/%d\n",ans1/x,ans2/x);
return 0;
}