[清华集训2016]温暖会指引我们前行

[清华集训2016]温暖会指引我们前行

UOJ
BZOJ
lct维护最大生成树和链上的边权和

#include<bits/stdc++.h>
using namespace std;
const int _=4e5+5;
int re(){
    int x=0,w=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x*w;
}
int n,m,cnt,top;
int f[_],s[_],ins[_],w[_],id[_],fa[_],rev[_],st[_],ch[2][_],val[_];
struct edge{int u,v,t,l;}e[_];
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
bool son(int x){return x==ch[1][fa[x]];}
bool isrt(int x){return x^ch[0][fa[x]]&&x^ch[1][fa[x]];}
void rever(int x){if(x)swap(ch[0][x],ch[1][x]),rev[x]^=1;}
void pd(int x){if(rev[x])rever(ch[0][x]),rever(ch[1][x]),rev[x]=0;}
void pu(int x){
	s[x]=s[ch[0][x]]+s[ch[1][x]]+val[x];id[x]=x;
	if(ch[0][x]&&w[id[ch[0][x]]]<w[id[x]])id[x]=id[ch[0][x]];
	if(ch[1][x]&&w[id[ch[1][x]]]<w[id[x]])id[x]=id[ch[1][x]];
}
void rotate(int x){
	int y=fa[x],z=fa[y],k=son(x);
	ch[k][y]=ch[k^1][x];if(ch[k][y])fa[ch[k][y]]=y;
	fa[x]=z;if(!isrt(y))ch[son(y)][z]=x;
	fa[y]=x;ch[k^1][x]=y;pu(y);
}
void splay(int x){
	st[top=1]=x;
	for(int i=x;!isrt(i);i=fa[i])st[++top]=fa[i];
	while(top)pd(st[top--]);
	for(int y=fa[x];!isrt(x);rotate(x),y=fa[x])
		if(!isrt(y))rotate(son(x)^son(y)?x:y);
	pu(x);
}
void access(int x){for(int y=0;x;y=x,x=fa[x])splay(x),ch[1][x]=y,pu(x);}
void makert(int x){access(x);splay(x);rever(x);}
void split(int x,int y){makert(x);access(y);splay(y);}
void cut(int x,int y){split(x,y);ch[0][y]=fa[x]=0;}
void link(int x,int y){makert(x);fa[x]=y;}
int main(){
    n=re(),m=re();
	for(int i=1;i<=n;i++)f[i]=i;
	char op[10];
	memset(w,63,sizeof(w));
	while(m--){
		scanf("%s",op);
		if(op[0]=='f'){
			int x=re()+1;
			e[x].u=re()+1,e[x].v=re()+1;
			e[x].t=re(),e[x].l=re();
			if(find(e[x].u)==find(e[x].v)){
				split(e[x].u,e[x].v);
				int k=id[e[x].v];
				if(e[k-n].t<e[x].t)
					cut(e[k-n].u,k),cut(e[k-n].v,k),ins[k-n]=0;
				else continue;
			}
			else f[f[e[x].u]]=f[e[x].v];
			w[x+n]=e[x].t;val[x+n]=e[x].l;
			link(x+n,e[x].u);link(x+n,e[x].v);
			ins[x]=1;
		}
		if(op[0]=='c'){
			int x=re()+1,l=re();
			if(ins[x]){
				makert(x+n);
				val[x+n]=l;pu(x+n);
			}
		}
		if(op[0]=='m'){
			int x=re()+1,y=re()+1;
			if(find(x)^find(y)){puts("-1");continue;}
			split(x,y);
			printf("%d\n",s[y]);
		}
	}
	return 0;
}
posted @ 2018-12-13 14:19  sdzwyq  阅读(274)  评论(0编辑  收藏  举报