跳到正文

题解

题解:AT_abc406_f [ABC406F] Compare Tree Weights

Collapsarr约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟

版本

  1. v1当前

AT_abc406_f 题解

赛时没看到 f 亏大了。

考虑将树拍成一个 dfn 序,并求出来每一个点在 dfn 序中的起始点和终点,那么查询操作查询的是起始点较晚的点的子树的权值,因为后遍历到的点子树中不包含所需要断开的边,相当于在 dfn 序中跑区间询问,修改操作相当于在 dfn 序中跑单点修改,难道不是莫队?

考虑带修莫队,和正常的树上莫队的区别是本题不需要考虑 lca 的贡献,其它的按照正常的带修莫队跑就可以了。

code

C++
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'

int read()
{
	int x = 0,f = 1;
	char ch = getchar();
	while(ch<'0'||'9'<ch)
	{
		if(ch=='-')
		{
			f = -1;
		}
		ch = getchar();
	}
	while('0'<=ch&&ch<='9')
	{
		x = (x<<3) + (x<<1) + ch - '0';
		ch = getchar();
	}
	return x * f;
}

const int inf = 1e18,N = 1e6 + 10;

int n,head[N],tot,m,oto,ans[N],sum1,sum2,B,id[N];
int dfn[N],a[N],cnt,be[N],ed[N];
pair<int,int> e[N],u[N];
bool falg[N];

struct node
{
	int u,v;
}edge[N];

struct que
{
	int l,r,ti,id;
}q[N];

bool operator<(que x,que y)
{
	return (id[x.l]==id[y.l])?((id[x.r]==id[y.r])?(x.ti<y.ti):(x.r<y.r)):(x.l<y.l);
}

void add(int u,int v)
{
	edge[++tot] = {head[u],v};
	head[u] = tot;
}

void dfs(int u,int fa)
{
	dfn[++cnt] = u,be[u] = cnt;
	for(int i = head[u];i;i = edge[i].u)
	{
		int v = edge[i].v;
		if(v!=fa)
		{
			dfs(v,u);
		}
	}
	ed[u] = cnt;
}

inline void add(int it)
{
	falg[it] = 1;
	sum1 += a[it];
}

inline void del(int it)
{
	falg[it] = 0;
	sum1 -= a[it];
}

signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	n = read();
	B = pow(n,2.0/3);
	for(int i = 1,u,v;i<n;i++)
	{
		u = read(),v = read();
		e[i] = {u,v};
		add(u,v),add(v,u);
		a[i] = 1;
		id[i] = (i-1) / B + 1;
	}
	a[n] = 1;
	dfs(1,0);
	m = read();
	int ti = 0;
	for(int i = 1,op,x,y,w;i<=m;i++)
	{
		op = read();
		if(op==1)
		{
			u[++ti] = {read(),read()};
		}
		else
		{
			w = read();
			x = e[w].first,y = e[w].second;
			if(be[x]<be[y])
			{
				swap(x,y);
			}
			q[++oto] = {be[x],ed[x],ti,oto};
		}
	}
	sort(q+1,q+1+oto);
	int l = q[1].l,r = q[1].l - 1;
	ti = 0;
	sum2 = n;
	for(int i = 1;i<=oto;i++)
	{
		while(l>q[i].l)
		{
			add(dfn[--l]);
		}
		while(r<q[i].r)
		{
			add(dfn[++r]);
		}
		while(l<q[i].l)
		{
			del(dfn[l++]);
		}
		while(r>q[i].r)
		{
			del(dfn[r--]);
		}
		while(ti<q[i].ti)
		{
			++ti;
			if(falg[u[ti].first])
			{
				sum1 += u[ti].second;
			}
			a[u[ti].first] += u[ti].second;
			sum2 += u[ti].second;
		}
		while(ti>q[i].ti)
		{
			if(falg[u[ti].first])
			{
				sum1 -= u[ti].second;
			}
			a[u[ti].first] -= u[ti].second;
			sum2 -= u[ti].second;
			ti--;
		}
		ans[q[i].id] = abs(sum2-2*sum1);
	}
	for(int i = 1;i<=oto;i++)
	{
		cout<<ans[i]<<endl;
	}
	return 0;
}
原文