Description
Solution
首先意识到这是一个最小生成树问题,但需要先满足所选边权值最小值最大,所以我们可以二分这个最小值,再用kruskal来check是否能成树
然而最后需要计算任意两点路径上最小边权的和,貌似可以暴力水过去
Code
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef long long ll;
const ll inf=1e18+10;
const int maxn = 1e4 + 7;
const int maxm = 5e5 + 7;
int n,m;
int fa[maxn];
int find(int x){return x == fa[x] ? x:fa[x] = find(fa[x]);}
struct Edge{
int u,v;
ll w;
}edge[maxm<<1];
bool cmp(Edge x, Edge y) {
return x.w < y.w;
}
inline void init() {
for(int i = 1;i <= n;++i) fa[i] = i;
}
bool check(int lim) {
if(m - lim + 1 < n - 1) return false;
int cnt = 0;init();
for(int i = lim;i <= m;++i) {
int u = edge[i].u, v = edge[i].v, w = edge[i].w;
int f1 = find(u), f2 = find(v);
if(f1 == f2) continue;
fa[f1] = f2;
cnt++;
}
return cnt == n - 1;
}
struct node{
int u,v;
ll w;
int next;
}e[maxn<<1];
int ecnt,head[maxn<<1];
inline void add(int u,int v,ll w) {
e[++ecnt] = (node) {u,v,w,head[u]}, head[u] = ecnt;
}
void build(int lim) {
int cnt = 0;init();
for(int i = lim;i <= m;++i) {
int u = edge[i].u, v = edge[i].v, w = edge[i].w;
int f1 = find(u), f2 = find(v);
if(f1 == f2) continue;
fa[f1] = f2;
cnt++;
add(u,v,w);add(v,u,w);
// debug2(u,v);
if(cnt == n - 1) break;
}
}
ll siz[maxn], dis[maxn];
ll sum = 0, res = 0;
inline ll MIN(ll x,ll y){
return x < y ? x : y;
}
void dfs(int u,int f) {
for(int i = head[u];i;i = e[i].next)
{
int v=e[i].v;
if (v==f) continue;
ll w=e[i].w;
dis[v]=MIN(dis[u],w);
sum+=dis[v];
dfs(v,u);
}
}
int main(int argc, char const *argv[]) {
scanf("%d %d",&n,&m);
for(int i = 1,u,v,w;i <= m;++i) {
scanf("%d %d %d",&u,&v,&w);
edge[i] = (Edge){u,v,w};
}sort(edge+1,edge+1+m,cmp);
int l = 1, r = m, mid, ans = 0;
while(l <= r) {
mid = (l + r) >> 1;
if(check(mid)){l = mid + 1;ans = mid;}
else r = mid - 1;
}
build(ans);
for (int i=1; i<=n; i++){
dis[i]=inf;
dfs(i,-1);
res+=sum;
sum=0;
}
printf ("%lld\n",res/2);
return 0;
}