思路:检验函数中,先初始化每个节点的下标,每调用检验函数就从新使用一次并查集(并查集的时间复杂度非常低),然后,就看当一条路的价值val<=假设最大值x时,就把他们连接起来。
#include<iostream> #include<algorithm> using namespace std; const int maxn = 1e4 + 10; int n, m, s, t, st[maxn << 1], en[maxn << 1], val[maxn << 1]; int l = maxn, r, ans, mid, fa[maxn]; //并查集 int getfa(int x){ if (fa[x] == x)return x; return fa[x] = getfa(fa[x]); } //并查集判断 bool find(int x, int y){ return getfa(x) == getfa(y); } //并查集合并 void H_(int x, int y){ if (!find(x, y))fa[getfa(x)] = fa[getfa(y)]; } bool check(int x){ for (int i = 1; i <= n; ++i)fa[i] = i; for (int i = 1; i <= m;++i) if (val[i] <= x)H_(st[i], en[i]); return find(s, t); } void half(){ while (l <= r){ mid = (l + r) >> 1; if (check(mid)){ ans = mid; r = mid - 1; } else l = mid + 1; } } int main(){ cin >> n >> m >> s >> t; for (int i = 1; i <= m; ++i) { cin >> st[i] >> en[i] >> val[i]; l = min(l, val[i]); r = max(r, val[i]); } half(); //二分 cout << ans << endl; }