60分蒟蒻求助/kel
查看原帖
60分蒟蒻求助/kel
118000
returnG楼主2020/6/29 20:36

TLE+WA,看了题解还是错了

评测记录:https://www.luogu.com.cn/record/34740541

辣鸡代码附上:

#include <bits/stdc++.h>
using namespace std;
long long n,m,mi=0,ans=999999999;
long long f[1000005];
long long find(long long x){
	if(f[x]==x)return x;
	return f[x]=find(f[x]);
}
void uni(long long x,long long y){
	long long fx=find(x),fy=find(y);
	if(fx!=fy)f[fx]=fy;
}
struct edge{
	long long x;
	long long y;
	long long z;
}e[3000005];
bool b[1000005];
bool cmp(edge x,edge y){
	return x.z<y.z;
}
struct line{
	long long to;
	long long num;
};
vector<line>ed[1000005];
long long lg[1000005],dep[1000005];
long long fa[1000005][30];
long long maxx[1000005][30],minn[1000005][30];
void dfs(long long u,long long fath){
	fa[u][0]=fath;
	dep[u]=dep[fath]+1;
	for(long long i=1;i<=lg[dep[u]];i++){
		fa[u][i]=fa[fa[u][i-1]][i-1];
	}
	for(long long i=0;i<ed[u].size();i++){
		long long v=ed[u][i].to;
		if(v==fath)continue;
		maxx[v][0]=ed[u][i].num;
		minn[v][0]=-999999999;
		dfs(v,u);
	}
}
void cal(){
	for(long long k=1;k<=lg[n];k++){
		for(long long j=1;j<=n;j++){
			maxx[j][k]=max(maxx[j][k-1],maxx[fa[j][k-1]][k-1]);
			minn[j][k]=max(minn[j][k-1],minn[fa[j][k-1]][k-1]);
			if(maxx[j][k-1]<maxx[fa[j][k-1]][k-1])minn[j][k]=max(minn[j][k],maxx[j][k-1]);
			else if(maxx[j][k-1]>maxx[fa[j][k-1]][k-1])minn[j][k]=max(minn[j][k],maxx[fa[j][k-1]][k-1]);
		}
	}
}
long long LCA(long long x,long long y){
	if(dep[x]<dep[y])swap(x,y);
	while(dep[x]>dep[y]){
		x=fa[x][lg[dep[x]-dep[y]]-1];
	}
	if(x==y)return y;
	for(long long k=dep[x];k>=0;k--){
		if(fa[x][k]!=fa[y][k]){
			x=fa[x][k];
			y=fa[y][k];
		}
	}
	return fa[x][0];
}
long long qmax(long long u,long long v,long long d){
	long long anss=-999999999;
	for(long long i=lg[n];i>=0;i--){
		if(dep[fa[u][i]]>=dep[v]){
			if(d!=maxx[u][i])anss=max(anss,maxx[u][i]);
			else anss=max(anss,minn[u][i]);
			u=fa[u][i];
		}
	}
	return anss;
}
int main() {
	scanf("%lld%lld",&n,&m);
	for(long long i=1;i<=n;i++)f[i]=i;
	for(long long i=1;i<=m;i++){
		long long x,y,z;
		scanf("%lld%lld%lld",&x,&y,&z);
		e[i].x=x;
		e[i].y=y;
		e[i].z=z;
	}
	sort(e+1,e+m+1,cmp);
	for(long long i=1;i<=m;i++){
		if(find(e[i].x)==find(e[i].y))continue;
		uni(e[i].x,e[i].y);
		mi+=e[i].z;
		b[i]=1;
		ed[e[i].x].push_back((line){e[i].y,e[i].z});
		ed[e[i].y].push_back((line){e[i].x,e[i].z});
	}
	for(long long i=1;i<=n;i++)lg[i]=lg[i-1]+(1<<lg[i-1]==i);
	dfs(1,0);
	minn[1][0]=-999999999;
	cal();
	for(long long i=1;i<=m;i++){
		if(b[i])continue;
		long long lca=LCA(e[i].x,e[i].y);
		long long maxu=qmax(e[i].x,lca,e[i].z);
		long long maxv=qmax(e[i].y,lca,e[i].z);
		ans=min(ans,mi-max(maxu,maxv)+e[i].z);
	}
	printf("%lld",ans);
	return 0;
}
2020/6/29 20:36
加载中...