P1396 营救(并查集+二分)

思路:检验函数中,先初始化每个节点的下标,每调用检验函数就从新使用一次并查集(并查集的时间复杂度非常低),然后,就看当一条路的价值val<=假设最大值x时,就把他们连接起来。

#include<iostream>
#include<algorithm>
using namespace std; const int maxn = 1e4 + ;
int n, m, s, t, st[maxn << ], en[maxn << ], val[maxn << ];
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 = ; i <= n; ++i)fa[i] = i;
for (int i = ; i <= m;++i)
if (val[i] <= x)H_(st[i], en[i]);
return find(s, t);
} void half(){
while (l <= r){
mid = (l + r) >> ;
if (check(mid)){ ans = mid; r = mid - ; }
else l = mid + ;
}
} int main(){
cin >> n >> m >> s >> t;
for (int i = ; i <= m; ++i)
{
cin >> st[i] >> en[i] >> val[i];
l = min(l, val[i]); r = max(r, val[i]);
}
half(); //二分
cout << ans << endl;
}
上一篇:C++内存管理(超长,例子很详细,排版很好)


下一篇:python的time模块总结