[dfs序+線段樹] codeforces 343D. Water Tree

題意:
給出一棵樹,節點權值爲true或者false,初始每個節點權值爲false,維護兩種操作。

  • 形如1 x:把x節點及其子樹的值賦爲true。
  • 形如2 x:把x節點及其到根節點的祖先賦值爲false。
  • 形如3 x:問x節點的值。

題解:
由於要對子樹進行操作,先求出dfs序,用線段樹即可快速維護子樹。
然而發現還要對祖先操作,dfs序對子樹和祖先顯然不能同時維護。
稍微轉換下思路,要維護祖先,也就是祖先下面的所有子節點都能影響到祖先,並且操作1和操作2對一個節點的值的影響是互斥的,最後一次影響的就是當前的值了。
於是用兩棵線段樹維護操作1的時間戳,操作2的時間戳,查詢時比較哪個操作的時間戳更靠後。
操作1的時間戳不需要往上更新,操作2的時間戳需要往上更新。

#include<bits/stdc++.h>
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int N = 5e5+15;
vector<int>G[N];
int lazy[N<<2], tree[N<<2], lazy1[N<<2], tree1[N<<2];
int stp = 1, in[N], out[N], id[N];
void dfs(int rt, int f){
    in[rt] = stp, id[stp++] = rt;
    for(auto& v : G[rt]){
        if(v != f) dfs(v, rt);
    }
    out[rt] = stp-1;
}
inline void push_up(int rt, int *tree, int* lazy){
    tree[rt] = max(tree[rt<<1], tree[rt<<1|1]);
}
void build(int rt, int l, int r, int *tree, int *lazy){
    tree[rt] = lazy[rt] = 0;
    if(l == r) return;
    int mid = (l+r) >> 1;
    build(lson, tree, lazy);
    build(rson, tree, lazy);
}
inline void push_down(int rt, int* tree, int* lazy){
    if(lazy[rt] != 0){
        tree[rt<<1] = tree[rt<<1|1] = lazy[rt<<1] = lazy[rt<<1|1] = lazy[rt];
        lazy[rt] = 0;
    }
}
void update(int rt, int l, int r, int ql, int qr, int val, int* tree, int* lazy, int f){
    if(ql <= l && qr >= r){
        lazy[rt] = val;
        tree[rt] = val;
        return;
    }
    push_down(rt, tree, lazy);
    int mid = (l+r) >> 1;
    if(ql <= mid) update(lson, ql, qr, val, tree, lazy, f);
    if(qr > mid) update(rson, ql, qr, val, tree, lazy, f);
    if(f) push_up(rt, tree, lazy);
}
int query(int rt, int l, int r, int ql, int qr,int *tree, int *lazy, int f){
    if(ql <= l && qr >= r){
        return tree[rt];
    }
    push_down(rt, tree, lazy);
    int mid = (l+r) >> 1;
    int res = 0;
    if(ql <= mid) res = max(res, query(lson, ql, qr, tree, lazy, f));
    if(qr > mid) res = max(res, query(rson, ql, qr, tree, lazy, f));
    if(f) push_up(rt, tree, lazy);
    return res;
}
int main(){
    int n;
    scanf("%d", &n);
    for(int i = 1; i < n; ++i){
        int a, b;
        scanf("%d%d", &a, &b);
        G[a].push_back(b);
        G[b].push_back(a);
    }
    dfs(1, -1);
    --stp;
    build(1, 1, stp, tree, lazy);
    build(1, 1, stp, tree1, lazy1);
    int q;
    scanf("%d", &q);
    for(int i = 1; i <= q; ++i){
        int t, v;
        scanf("%d%d", &t, &v);
        if(t == 1) update(1, 1, stp, in[v], out[v], i, tree, lazy, 0);
        else if(t == 2) update(1, 1, stp, in[v], in[v], i, tree1, lazy1, 1);
        else{
            int a = query(1, 1, stp, in[v], in[v], tree, lazy, 0);
            int b = query(1, 1, stp, in[v], out[v], tree1, lazy1, 1);
            printf("%d\n", a>b);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章