bzoj 1050 [ HAOI 2006 ] 旅行comf —— 并查集
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1050
没思路的话想想暴力就好了...
首先,比值最小就是确定最小值后最大值最小;
怎样确定最小值?其实就是暴枚;
然后从最小值往上加边,并查集维护连通性,当 s 和 t 连通时的边就是最小的最大值。
代码如下:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int const maxn=505,maxm=5005,inf=0x3f3f3f3f; int n,m,fa[maxn],s,t,up,dn; struct N{int u,v,w;}ed[maxm]; bool cmp(N x,N y){return x.w<y.w;} int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);} int gcd(int a,int b){return b?gcd(b,a%b):a;} int main() { scanf("%d%d",&n,&m); for(int i=1;i<=m;i++)scanf("%d%d%d",&ed[i].u,&ed[i].v,&ed[i].w); scanf("%d%d",&s,&t); sort(ed+1,ed+m+1,cmp); up=inf; dn=1; for(int i=1;i<=m;i++) { for(int j=1;j<=n;j++)fa[j]=j; int mx=-1; for(int k=i;k<=m;k++) { int u=ed[k].u,v=ed[k].v; if(find(u)!=find(v))fa[find(u)]=find(v); if(find(s)==find(t)){mx=ed[k].w; break;} } if(mx!=-1&&1.0*up/dn>1.0*mx/ed[i].w)up=mx,dn=ed[i].w; } if(up==inf)printf("IMPOSSIBLE\n"); else { int g=gcd(up,dn); up/=g; dn/=g; if(dn==1)printf("%d\n",up); else printf("%d/%d\n",up,dn); } return 0; }