dfs Order and Its Applications

dfs subtree sequence is used to handle a class of problems, the sub-tree can be transformed into the problem zone, segment tree or tree to aid the processing array. To update the order to dfs number when entering the node in the node array, go out when the update array, and i is in the subtree rooted operation can become interval [in [i] ... out [i] ] of the operation.

int in[100005],out[100005];
int tot = 1;

void dfs(int x,int fa)
{
	in[x] = tot ++;
	for (int i = 0; i < g[x].size(); i++)
	{
		int t = g[x][i];
		if( t == fa ) continue;
		dfs(t,x);
	}
	out[x] = tot - 1;
}

Title: Given a tree rooted at 1, has two operating. Operation of the node weights x 1 XOR value 1, the operation 2 x query to the root node of the subtree, and weight.
Idea: use dfs order to become sub-tree section and ask, Fenwick tree maintenance can be.

#include <cstdio>
#include <vector>
using namespace std;

vector<int> g[100005];
int n,num[100005];
int in[100005],out[100005],c[100005];
int tot = 1;

void dfs(int x,int fa)
{
	in[x] = tot ++;
	for (int i = 0; i < g[x].size(); i++)
	{
		int t = g[x][i];
		if( t == fa ) continue;
		dfs(t,x);
	}
	out[x] = tot - 1;
}

int lowbit(int x)
{
	return x & (-x);
}

void update(int x,int k)
{
	for (int i = x; i <= n; i += lowbit(i))
	{
		c[i] += k;
	}
}

int query(int x)
{
	int res = 0;
	for (int i = x; i > 0; i-= lowbit(i))
	{
		res += c[i];
	}
	return res;
}

int main()
{
	scanf("%d",&n); 
	for (int i = 1; i < n; i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		g[x].push_back(y); 
	}
	dfs(1);
	for (int i = 1; i <= n; i++)
	{
		update(i,1);
		num[i] = 1;
	} 
	int m;
	scanf("%d",&m);
	for (int i = 1; i <= m; i++)
	{
		getchar();
		char t;
		int x;
		scanf("%c%d",&t,&x);
		if( t == 'Q' )
		{
			printf("%d\n",query(out[x]) - query(in[x]-1));

		}else
		{
			if( num[x] == 0 )
			{
				num[x] = 1;
				update(in[x],1);
			}else
			{
				num[x] = 0;
				update(in[x],-1);
			}
		}
	}
	return 0;
}
Published 132 original articles · won praise 6 · views 7914

Guess you like

Origin blog.csdn.net/weixin_44316314/article/details/105039262