严格次小生成树 56pts WA #9~#13 求调
查看原帖
严格次小生成树 56pts WA #9~#13 求调
1046448
Polaris_flame楼主2025/1/20 20:50

rt,

写的倍增+lca,一直过不了...

#include<bits/stdc++.h>
#define FL(i,a,b) for(ll i=(a);i<=(b);i++)
#define FR(i,a,b) for(ll i=(a);i>=(b);i--)
#define ll long long
#define PII pair<ll,ll>
using namespace std;
const ll MAXN = 1e5 + 10;
const ll MAXM = 3e5 + 10;
const ll inf = 1e18;
ll n,m;
ll ans=inf,sum=0;
ll fa[MAXN],f[20][MAXN],dep[MAXN];
PII mx[20][MAXN];
vector<PII>G[MAXN];
struct edge{
	ll u,v;
	ll w;
}e[MAXM];
bool vis[MAXM];
bool cmp(edge p,edge q){
	return p.w<q.w;
}
ll find(ll x){
	if(fa[x]==x) return x;
	return fa[x]=find(fa[x]);
}
void kruskal(){
	FL(i,1,n) fa[i]=i;
	sort(e+1,e+m+1,cmp);
	FL(i,1,m){
		ll u=find(e[i].u);
		ll v=find(e[i].v);
		if(u==v) continue;
		fa[u]=v;
		vis[i]=1;
		G[e[i].u].push_back({e[i].v,e[i].w});
		G[e[i].v].push_back({e[i].u,e[i].w});
		sum+=e[i].w;
	} 
}
PII operator+(PII p,PII q){
	if(p.first==q.first) return {p.first,max(p.second,q.second)};
	else return {max(p.first,q.first),max(min(p.first,q.first),max(p.second,q.second))};
}
void dfs(ll u,ll fth){
	dep[u]=dep[fth]+1;
	for(auto i:G[u]){
		ll v=i.first;
		ll w=i.second;
		if(v==fth) continue;
		f[0][v]=u;
		mx[0][v]={w,0};
		dfs(v,u);
	}
	FL(i,1,19) f[i][u]=f[i-1][f[i-1][u]],mx[i][u]=mx[i-1][u]+mx[i-1][f[i-1][u]];
}
ll lca(ll x,ll y,ll w){
	ll res=0;
	if(dep[x]<dep[y]) swap(x,y);
	FR(i,19,0){
		if(dep[f[i][x]]>=dep[y]){
			if(mx[i][x].first!=w) res=max(res,mx[i][x].first);
			else if(mx[i][x].second) res=max(res,mx[i][x].second);
			x=f[i][x];
		} 
	}
	if(x==y) return res;
	FR(i,19,0){
		if(f[i][x]!=f[i][y]){
			if(mx[i][x].first!=w) res=max(res,mx[i][x].first);
			else if(mx[i][x].second) res=max(res,mx[i][x].second);
			if(mx[i][y].first!=w) res=max(res,mx[i][y].first);
			else if(mx[i][y].second) res=max(res,mx[i][y].second);
			x=f[i][x],y=f[i][y];
		}
	}
	if(mx[0][x].first!=w) res=max(res,mx[0][x].first);
	else if(mx[0][x].second) res=max(res,mx[0][x].second);
	if(mx[0][y].first!=w) res=max(res,mx[0][y].first);
	else if(mx[0][y].second) res=max(res,mx[0][y].second);
	return res;
}
signed main(){
	scanf("%lld%lld",&n,&m);
	FL(i,1,m) scanf("%lld%lld%lld",&e[i].u,&e[i].v,&e[i].w);
	kruskal();
//	printf("sum=%lld\n",sum);
	dfs(1,0);
	FL(i,1,m){
		if(vis[i]) continue;
		ll t=lca(e[i].u,e[i].v,e[i].w);
//		printf("(%lld %lld) %lld\n",t.first,t.second,e[i].w);
		if(t) ans=min(ans,sum-t+e[i].w);
	}
	printf("%lld\n",ans);
} 
2025/1/20 20:50
加载中...