ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

高级数据结构第六章E . 苹果树 (dfs+树状数组)

2021-06-14 20:04:56  阅读:206  来源: 互联网

标签:typedef ch 树状 int ll dfs maxn 苹果树


link

思路:

经典套路,通过dfs序将树上修改转化为线性修改,这样问题就转化为了单点修改,区间查询,用树状数组维护。
类似题

代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}
#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b, ll p)
{
    ll res = 1;
    while(b)
    {
        if(b & 1)res = res * a % p;
        a = a * a % p;
        b >>= 1;
    }
    return res;
}
const int inf = 0x3f3f3f3f;
#define PI acos(-1)

const int maxn=1e5+100;

struct BIT{
    ll n,tr[maxn];

    void init(){
        memset(tr,0,sizeof tr);
    }
    ll lowbit(ll x){
        return x&-x;
    }
    void update(ll pos,ll val){
        while(pos<=n){
            tr[pos]+=val;pos+=lowbit(pos);
        }
    }
    ll qask(ll pos){
        ll res=0;
        while(pos){
            res+=tr[pos];pos-=lowbit(pos);
        }
        return res;
    }

};

int n,m,a[maxn];
vector<int>g[maxn];
ll in[maxn],out[maxn],timetmp;
void dfs(int u,int fa){//dfs记录dfs序列
    in[u]=++timetmp;
    for(int i=0;i<g[u].size();i++){
        int j=g[u][i];
        if(j==fa) continue;
        dfs(j,u);
    }
    out[u]=timetmp;
}

int main()
{
    n=read;
    rep(i,1,n-1){
        int u=read,v=read;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(1,-1);
    BIT t;
    t.n=1e5;t.init();
    rep(i,1,n) t.update(in[i],1),a[i]=1;
    m=read;
    rep(i,1,m){
        char op[2];int x;
        cin>>op;x=read;
        if(op[0]=='C'){
           if(a[x]) t.update(in[x],-1);
           else t.update(in[x],1);
           a[x]=!a[x];
        }
        else{
            printf("%lld\n",t.qask(out[x])-t.qask(in[x]-1));
        }
    }
    return 0;
}

/*

**/

标签:typedef,ch,树状,int,ll,dfs,maxn,苹果树
来源: https://www.cnblogs.com/OvOq/p/14883146.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有