码迷,mamicode.com
首页 > 其他好文 > 详细

codevs1228 (dfs序+线段树)

时间:2017-07-31 21:14:13      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:set   build   ios   裸题   lazy   pac   区间   scanf   upd   

  • 总结:

第一次遇到dfs序的问题,对于一颗树,记录节点 i 开始搜索的序号 Left[i] 和结束搜索的序号 Righti[i],那么序号在 Left[i] ~ Right[i] 之间的都是节点 i 子树上的节点。

并且此序号与线段树中 L~R 区间对应,在纸上模拟了几遍确实如此,但暂时还未理解为何对应。

此题就是dfs序+线段树的裸题

  • 代码:
#include<iostream>
#include<vector>
#include<cstring>
#include<cstdio>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
const int maxn = 1e5+5;

int dfs_order=0, Right[maxn], Left[maxn], vis[maxn];
int sumv[maxn<<2], lazy[maxn<<2];
vector<int> G[maxn];

void push_up(int l, int r, int rt)
{
    sumv[rt]=sumv[rt<<1]+sumv[rt<<1|1];
}

void build(int l, int r, int rt)
{
    if(l==r)
    {
        //cout<<l<<endl;
        sumv[rt]=1;
        return;
    }
    int m=(l+r)/2;
    build(lson);
    build(rson);
    push_up(l, r, rt);
}

void update(int l, int r, int rt, int x, int v)
{
    if(l==r)
    {
        sumv[rt]+=v;
        return;
    }
    int m=(l+r)/2;
    if(x<=m) update(lson, x, v);
    if(m<x) update(rson, x, v);
    push_up(l, r, rt);
}

int query(int l, int r, int rt, int ql, int qr)
{
    if(ql<=l && r<=qr)
    {
        return sumv[rt];
    }
    int m=(l+r)/2, res;
    if(qr<=m) res=query(lson, ql, qr);
    else if(m<ql) res=query(rson, ql, qr);
    else res=query(lson, ql, qr)+query(rson, ql, qr);
    //cout<<"query "<<res<<endl;
    return res;
}

void dfs(int x)
{
    dfs_order++;
    Left[x]=dfs_order;
    //cout<<x<<" "<<Left[x]<<endl;
    for(int i=0; i<G[x].size(); ++i)
    {
        if(!vis[G[x][i]]) {vis[G[x][i]]=1;dfs(G[x][i]);}
    }
    Right[x]=dfs_order;
}

int main()
{
    int n, m;
    scanf("%d", &n);
    build(1, n, 1);
    for(int i=1; i<n; ++i)
    {
        int u, v;
        scanf("%d%d", &u, &v);
        G[u].push_back(v);
        G[v].push_back(u);
    }
    vis[1]=1;
    dfs(1);
    memset(vis, 0, sizeof vis);
    scanf("%d", &m);
    for(int i=1; i<=m; ++i)
    {
        char op;
        int t;
        cin>>op>>t;
        if(op==‘Q‘)
        {
            //cout<<Left[t]<<" "<<Right[t]<<endl;
            printf("%d\n", query(1, n, 1, Left[t], Right[t]));
        }
        else
        {
            if(!vis[t])
                update(1, n, 1, Left[t], -1);
            else
                update(1, n, 1, Left[t], 1);
            vis[t]=!vis[t];
        }
    }
    return 0;
}

 

codevs1228 (dfs序+线段树)

标签:set   build   ios   裸题   lazy   pac   区间   scanf   upd   

原文地址:http://www.cnblogs.com/xiepingfu/p/7265672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!