dfs + segment tree data structure class zhrt

zhrt data structure courses

I think this topic is a dfs + tree line a little bit of thinking

Although it looks like a tree with a chain can be split to write, but this time the title card tree section

Because before a tree have been writing this section, it has been thought that the update interval, want dfs + tree line, there is little thought to understand

Later we learned that this range can be converted into a single point update update is to check a child node of a tree, if there can be sub-tree to the root node, then the node must also be the root node.

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <stack>
#include <map>
#include <string>
#define inf 0x3f3f3f3f
#define inf64 0x3f3f3f3f3f3f3f3f
using namespace std;
const int maxn = 4e5 + 10;
int sum[maxn * 4];

void push_up(int id)
{
	sum[id] = sum[id << 1 | 1] + sum[id << 1];
}

void build(int id,int l,int r)
{
	if(l==r)
	{
		sum[id] = 0;
		return;
	}
	int mid = (l + r) >> 1;
	build(id << 1, l, mid);


	if (x <= mid) ans += query(id << 1, l, mid, x, y);
int el[maxn], er[maxn], tot = 0, head[maxn], cnt;
struct node
{
	int v, nxt;
	node(int v=0,int nxt=0):v(v),nxt(nxt){}
}ex[maxn];

void init()
{
	memset(head, -1, sizeof(head));
	tot = 0, cnt = 0;
}

void add(int u,int v)
{
	ex[cnt] = node(v, head[u]);
	head[u] = cnt++;
	ex[cnt] = node(u, head[v]);
	head[v] = cnt++;
	// printf("u=%d v=%d\n", u, v);
}

void dfs(int u,int pre)
{
	el[u] = ++tot;
	for(int i=head[u];i!=-1;i=ex[i].nxt)
	{
		int v = ex[i].v;
		if (v == pre) continue;
		dfs(v, u);
	}
	er[u] = tot;
	// printf("el[%d]=%d er[%d]=%d\n", u, el[u], u, er[u]);
}

int main()
{
	int t;
	scanf("%d", &t);
	while(t--)
	{
		init();
		int n, m;
		scanf("%d%d", &n, &m);
		build(1, 1, n);
		for(int i=1;i<n;i++)
		{
			int u, v;
			scanf("%d%d", &u, &v);
			add(u, v);
		}
		dfs(1, -1);
		while(m--)
		{
			int opt, x;
			scanf("%d%d", &opt, &x);
			if (opt == 0) update(1, 1, n, el[x], 1);
			if (opt == 1) update(1, 1, n, el[x], -1);
			if (opt == 2)
			{
				int ans = query(1, 1, n, el[x], er[x]);
				if (ans) printf("Yes\n");
				else printf("No\n");
			}
		}
	}
}

  

Guess you like

Origin www.cnblogs.com/EchoZQN/p/11334372.html