【BZOJ 2959】长跑

传送门


Problem

n n n 个点,用 1 1 1 n n n 的整数表示,每个点有点权,有以下三类操作:

  1. 连接 a a a b b b
  2. a a a 点的点权变为了 b b b
  3. 问一个人从 a a a出发,最后到达 b b b 所经过的点权之和最多为多少。

具体的要求如下:

当这个人到达一个地点时,他可以在这里的每一台刷卡机上都刷卡。但每台刷卡机只能刷卡一次,即使多次到达同一地点也不能多次刷卡。

注意:连接之后不一定是一棵树。


Solution

很久没写博客了。。。

如果这是一棵树,那这道题就很简单,只需 L C T \mathrm{LCT} LCT 维护一下就可以了。

当产生了一个环之后,最优的走法肯定是把环上的点都走完,然后再继续走。

于是就想到了通过缩点来消去环,缩点的权值就是环上的点权之后。

用一个单独的并查集维护缩点就可以了。

然后这道题有点卡常,加个读优就能过,代码中为了简洁就省略了。


Code

#include<stack>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 300005
using namespace std;
int a[N],father[N],belong[N];
int find(int x)  {return (father[x]==x)?x:father[x]=find(father[x]);}
int findroot(int x)  {return (belong[x]==x)?x:belong[x]=findroot(belong[x]);}
namespace LCT{
	int fa[N],val[N],sum[N],son[N][2],mark[N];
	bool Get(int x)  {return son[find(fa[x])][1]==x;}
	bool isroot(int x){
		int Dad=find(fa[x]);
		return (son[Dad][0]!=x)&&(son[Dad][1]!=x);
	}
	void pushup(int x)  {sum[x]=sum[son[x][0]]+sum[son[x][1]]+val[x];}
	void pushdown(int x){
		if(!mark[x])  return;
		swap(son[x][0],son[x][1]);
		mark[son[x][0]]^=1,mark[son[x][1]]^=1;
		mark[x]=0;
	}
	void Rotate(int x){
		int y=fa[x],z=fa[y];
		int k=Get(x),l=son[x][k^1];
		son[y][k]=l,fa[l]=(l?y:0);
		if(!isroot(y))  son[z][Get(y)]=x;fa[x]=z;
		son[x][k^1]=y,fa[y]=x;
		pushup(y),pushup(x);
	}
	stack<int>stk;
	void Splay(int x){
		stk.push(x);
		for(int i=x;!isroot(i);i=find(fa[i]))  stk.push(find(fa[i]));
		while(!stk.empty())  pushdown(stk.top()),fa[stk.top()]=find(fa[stk.top()]),stk.pop();
		while(!isroot(x)){
			int y=fa[x];
			if(!isroot(y))  Rotate(Get(x)==Get(y)?y:x);
			Rotate(x);
		}
	}
	void Access(int x){
		for(int i=0;x;i=x,x=find(fa[x]))
		  Splay(x),son[x][1]=i,pushup(x);
	}
	void Makeroot(int x){
		Access(x),Splay(x),mark[x]^=1;
	}
	void Link(int x,int y){
		Makeroot(x),fa[x]=y;
	}
	void Split(int x,int y){
		Makeroot(x),Access(y),Splay(y);
	}
}
using namespace LCT;
void dfs(int x,int y){
	if(!x)  return;
	father[find(x)]=find(y),pushdown(x);
	if(x!=y)  val[y]+=val[x];
	dfs(son[x][0],y),dfs(son[x][1],y);
	son[x][0]=son[x][1]=0;
}
int main(){
	int n,m,i,op,x,y;
	scanf("%d%d",&n,&m);
	for(i=1;i<=n;++i){
		belong[i]=father[i]=i;
		scanf("%d",&val[i]),a[i]=val[i];
	}
	for(i=1;i<=m;++i){
		scanf("%d%d%d",&op,&x,&y);
		if(op==1){
			x=find(x),y=find(y);
			if(x!=y){
				int r1=findroot(x),r2=findroot(y);
				if(r1!=r2)  belong[r2]=r1,Link(x,y);
				else  Split(x,y),dfs(y,y),pushup(y);
			}
		}
		else  if(op==2){
			int xx=find(x);
			Access(xx),Splay(xx);
			val[xx]+=(y-a[x]),a[x]=y;
			pushup(xx);
		}
		else{
			x=find(x),y=find(y);
			if(findroot(x)!=findroot(y))  {puts("-1");continue;}
			Split(x,y),printf("%d\n",sum[y]);
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值