HDU3974.Assign the task(DFS序&&线段树)

Assign the task

**题意:**给你一个有向树,然后可以执行两种操作:

1.修改:将该点的子树节点都修改为同一个值。
2.查询:单点查询,查询该点的值。

**题解:**首先对于一个树形结构,可以用DFS序将它转化为线性结构,ll[x]和rr[x]为该店的左右端点,然后用那个线段树维护区间。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e4 + 5;
int cnt;
vector<int>g[maxn];
int ll[maxn], rr[maxn];
bool vis[maxn];
int n, m, u, v;
void dfs(int x){
	ll[x] = ++cnt;
	for (int y : g[x])
		dfs(y);
	rr[x] = cnt;
}
struct node{
	int l, r;
	int lazy;
	int val;
}tree[maxn*4];
void build(int root, int l, int r){
	tree[root].l = l;
	tree[root].r = r;
	tree[root].val = -1;
	tree[root].lazy = 0;
	if (l == r)	return;
	int mid = (l + r) >> 1;
	build(root << 1, l, mid);
	build(root << 1 | 1, mid+1, r);
}
void pushdown(int root){
	if (tree[root].lazy){
		tree[root << 1].lazy = tree[root].lazy;
		tree[root << 1 | 1].lazy = tree[root].lazy;
		tree[root << 1].val = tree[root].lazy;
		tree[root << 1 | 1].val = tree[root].lazy;
		tree[root].lazy = 0;
	}
}
void update(int root, int l, int r, int add){
	if (tree[root].l >=l&& tree[root].r<=r){
		tree[root].val = add;
		tree[root].lazy = add;
		return;
	}
	if (tree[root].l > r || tree[root].r < l)
		return;
	if (tree[root].lazy) pushdown(root);
	update(root << 1, l, r, add);
	update(root << 1 | 1, l, r, add);
}
int query(int root, int x){
	if (tree[root].l ==x&&tree[root].r==x){
		return tree[root].val;
	}
	if (tree[root].lazy) pushdown(root);
	int mid = (tree[root].l + tree[root].r) >> 1;
	if (x<=mid ) return query(root << 1, x);
	else return query(root <<1 | 1, x);
}
int main(){
	ios::sync_with_stdio(0);
	int T;
	int k = 0;
	cin >> T;
	while (T--){
		memset(vis, 0, sizeof vis);//清空操作,wa了两发
		memset(ll, 0, sizeof ll);
		memset(rr, 0, sizeof rr);
		k++;
		cnt = 0;
		cout << "Case #" << k << ":" << endl;
		cin >> n;
		for (int i = 1; i <= n; i++)
			g[i].clear();
		for (int i = 1; i <= n - 1; i++){
			cin >> u >> v;
			g[v].push_back(u);
			vis[u] = 1;
		}
		for (int i = 1; i <= n; i++){
			if (!vis[i]) dfs(i);
		}
		build(1, 1, n);
		cin >> m;
		while (m--){
			char ch; int x,y;
			cin >> ch;
			if (ch == 'C'){
				cin >> x;
				cout << query(1, ll[x]) << endl;
			}
			else{
				cin >> x >> y;
				update(1, ll[x], rr[x], y);
			}
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值