题目链接:
https://www.lydsy.com/JudgeOnline/problem.php?id=1050
题目大意:
给你一个无向图,N(N<=500)个顶点, M(M<=5000)条边,每条边有一个权值Vi(Vi<30000)。给你两个顶点S和T,求一条路径,使得路径上最大边和最小边的比值最小。如果S和T之间没有路径,输出”IMPOSSIBLE”,否则输出这个比值,如果需要,表示成一个既约分数。 备注: 两个顶点之间可能有多条路径。
思路:
枚举最小的边,逐步按照权值从小到大将边加入并查集中,直到s-t连通为止。
每次保留最小的ans(分数)即可。
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);//不可再使用scanf printf
#define Max(a, b) ((a) > (b) ? (a) : (b))//禁用于函数,会超时
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Mem(a) memset(a, 0, sizeof(a))
#define Dis(x, y, x1, y1) ((x - x1) * (x - x1) + (y - y1) * (y - y1))
#define MID(l, r) ((l) + ((r) - (l)) / 2)
#define lson ((o)<<1)
#define rson ((o)<<1|1)
#define Accepted 0
#pragma comment(linker, "/STACK:102400000,102400000")//栈外挂
using namespace std;
inline int read()
{
int x=,f=;char ch=getchar();
while (ch<''||ch>''){if (ch=='-') f=-;ch=getchar();}
while (ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
} typedef long long ll;
const int maxn = + ;
const int MOD = ;//const引用更快,宏定义也更快
const int INF = 1e9 + ;
const double eps = 1e-; struct edge
{
int u, v, w;
edge(){}
edge(int u, int v, int w):u(u), v(v), w(w){}
bool operator < (const edge& a)const
{
return w < a.w;
}
};
vector<edge>e;
int p[maxn];
vector<int>G[maxn];
void addedge(int u, int v, int w)
{
e.push_back(edge(u, v, w));
G[u].push_back(e.size() - );
e.push_back(edge(v, u, w));
G[v].push_back(e.size() - );
}
int Find(int x)
{
return x == p[x] ? x : p[x] = Find(p[x]);
}
struct node
{
int a, b;
node(){}
node(int A, int B)
{
int g = __gcd(A, B);
a = A / g, b = B / g;
}
bool operator < (const node& tmp)const
{
return a * tmp.b < b * tmp.a;
}
}; int main()
{
int n, m, u, v, w, s, t;
scanf("%d%d", &n, &m);
while(m--)
{
scanf("%d%d%d", &u, &v, &w);
addedge(u, v, w);
}
scanf("%d%d", &s, &t);
sort(e.begin(), e.end());
m = e.size();
node ans(, );//最大
for(int start = ; start < m; start++)//枚举下限
{
for(int i = ; i <= n; i++)p[i] = i;//初始化并查集
int cnt = -INF;
for(int i = start; i < m; i++)
{
int u = e[i].u, v = e[i].v, w = e[i].w;
u = Find(u);
v = Find(v);
p[u] = v;
if(Find(s) == Find(t))
{
cnt = w;
break;
}
}
if(cnt == -INF)
{
break;
}
ans = min(ans, node(cnt, e[start].w));
}
if(ans.a == && ans.b == )puts("IMPOSSIBLE\n");
else if(ans.b != )printf("%d/%d\n", ans.a, ans.b);
else printf("%d\n", ans.a);
return Accepted;
}