TLE 求问是哪里挂了?
查看原帖
TLE 求问是哪里挂了?
227824
JK_LOVER楼主2020/7/29 14:32
#include<bits/stdc++.h>
using namespace std;
const int N = 501010;
int val[N],mx[N],si[N],c[N][2],fa[N],n,m,mx2[N];
bool r[N];
int read(){
	int x;scanf("%d",&x);return x;
}
bool nroot(int x)
{
	return c[fa[x]][1] == x || c[fa[x]][0] == x;
}
void pushr(int x)
{
	swap(c[x][1],c[x][0]);
	r[x] ^= 1;
}
void pushup(int x){
    int l=c[x][0],r=c[x][1];
         if(mx[l]>mx[r])mx[x]=mx[l],mx2[x]=max(mx2[l],mx[r]);
    else if(mx[r]>mx[l])mx[x]=mx[r],mx2[x]=max(mx2[r],mx[l]);
    else                mx[x]=mx[l],mx2[x]=max(mx2[l],mx2[r]);
         if(val[x]>mx[x]) mx2[x]=mx[x],mx[x]=val[x];
    else if(val[x]!=mx[x]&&val[x]>mx2[x])mx2[x]=val[x];
}
void pushdown(int x)
{
	if(r[x])
	{
		if(c[x][1]) pushr(c[x][1]);
		if(c[x][0]) pushr(c[x][0]);
		r[x] = 0;
	}
}
void rotate(int x)
{
	int y = fa[x],z = fa[y],k = c[y][1] == x,w = c[x][!k];
	if(nroot(y)) c[z][c[z][1] == y] = x;
	if(w) fa[w] = y;fa[x] = z;fa[y] = x;
	c[y][k] = w;c[x][!k] = y;
//	cout<<x<<endl;
	pushup(y);
} 
void push(int x)
{
//	cout<<x<<" "<<fa[x]<<endl;
	if(nroot(x)) push(fa[x]);
	pushdown(x);
}
void splay(int x)
{
//	cout<<x<<endl;
	push(x);
	while(nroot(x))
	{
		int y = fa[x],z = fa[y];
		if(nroot(y))
		{
			rotate(((c[y][1] == x)^(c[z][1] == y))?x:y);
		}
		rotate(x);
		pushup(x);
	}
}
void access(int x)
{
//	cout<<x<<endl;
	for(int y = 0;x;x = fa[y=x])
	splay(x),c[x][1] = y,pushup(x);
}	
void makeroot(int x)
{
	access(x);splay(x);pushr(x);
}
void split(int x,int y)
{
	makeroot(x);access(y);splay(y);
}
void link(int x,int y)
{
	split(x,y);fa[x] = y;
}
int findroot(int x)
{

	access(x);splay(x);
//	cout<<"12"<<endl;
	while(c[x][0]) x = c[x][0];
	return x;
}
struct E{
	int x,y,w;
}e[N<<1];
bool cmp(E a,E b)
{
	return a.w < b.w;
} 
bool Vis[N<<1];
long long tot = 0,Ans = 0x3f3f3f3f3f3f3f3f;
signed main()
{
	n = read();m = read();
	for(int i = 1;i <= m;i++){e[i].x = read();e[i].y = read();e[i].w = read();}
	sort(e+1,e+1+m,cmp);
	for(int i = 1;i <= m;i++)
	{
		int a = e[i].x,b = e[i].y;	
//		cout<<a<<" "<<b<<endl;
		if(findroot(a) != findroot(b))
		{
			tot += e[i].w;
			link(a,n+i);
			link(b,n+i);
			Vis[i] = 1;
			val[n+i] = e[i].w;
		}
	}
	for(int i = 1;i <= m;i++)
	{
		if(Vis[i]) continue;
		int a = e[i].x, b = e[i].y;
		split(a,b);
//		cout<<e[i].w<<" "<<mx[b]<<" "<<mx2[b]<<endl;
		Ans = min(e[i].w-(e[i].w>mx[b]?mx[b]:mx2[b])*1LL,Ans);
	}
//	cout<<tot<<" "<<Ans<<endl;
	cout<<tot+Ans<<endl;
}
2020/7/29 14:32
加载中...