sort一下O(n2)暴力枚举
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define rep(i,s,t) for(int i=s;i<=t;i++)
#define dwn(i,s,t) for(int i=s;i>=t;i--)
#define clr(x,c) memset(x,c,sizeof(x))
int read(){
int x=0;char c=getchar();
while(!isdigit(c)) c=getchar();
while(isdigit(c)) x=x*10+c-'0',c=getchar();
return x;
}
const int nmax=505;
const int maxn=5005;
const int inf=0x7f7f7f7f;
struct edge{
int u,v,d;
bool operator<(const edge&rhs) const{
return d<rhs.d;}
};
edge es[maxn];
int fa[nmax];
int find(int x){
return fa[x]==x?x:fa[x]=find(fa[x]);
}
int gcd(int a,int b){
return b==0?a:gcd(b,a%b);
}
int main(){
int n=read(),m=read();
rep(i,1,m) es[i].u=read(),es[i].v=read(),es[i].d=read();
sort(es+1,es+m+1);
int ta,tb,s=read(),t=read(),aa,ab;double ans=30005;
rep(i,1,m){
if(es[i].d==es[i-1].d) continue;
rep(j,1,n) fa[j]=j;
rep(j,i,m){
ta=find(es[j].u);tb=find(es[j].v);
if(ta!=tb) fa[ta]=tb;
else continue;
if(find(s)==find(t)) {
if(ans>es[j].d*1.0/es[i].d){
ans=es[j].d*1.0/es[i].d,aa=es[j].d,ab=es[i].d;
}
break;
}
}
}
//printf("%d %d %lf\n",aa,ab,ans);
if(ans==30005) printf("IMPOSSIBLE\n");
else if(aa%ab==0) printf("%d\n",aa/ab);
else{
int tmp=gcd(aa,ab);
printf("%d/%d\n",aa/tmp,ab/tmp);
}
return 0;
}
1050: [HAOI2006]旅行comf
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 2769 Solved: 1501
[Submit][Status][Discuss]
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
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