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;
}