POJ 3321 Apple Tree dfs序+线段树

题目链接

http://poj.org/problem?id=3321

题意

一颗苹果树,以1为根,含有n个结点,每个节点上都会张出苹果。现在给出m个询问
Q v代表修改v结点的状态,即有苹果就摘掉,没有苹果就让其长出苹果。
C v代表查询以v为根的子树中,包含的苹果个数。

思路

用dfs序的连续区间可以代表一个子树,线段树叶子节点存储对应dfs序的结点苹果的有无。然后用线段树更新查询.
用vector存图居然超时了。。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<map>
#define ll long long
using namespace std;
const int INF = ( 2e9 ) + 2;
const ll maxn = 4e5+100;
vector<int> g[maxn];
int col[maxn];
int p1[maxn],p2[maxn],con[maxn];
int index;
struct node
{
    int l,r,f;
}t[maxn*4];
struct edge
{
    int v,next;
}e[maxn*2];
int head[maxn];
int tot;
void add(int u,int v)
{
    e[tot].v=v;
    e[tot].next=head[u];
    head[u]=tot++;
}
void build(int root,int l,int r)
{
    t[root].l=l;
    t[root].r=r;
    t[root].f=0;
    if(l==r)
    {
        t[root].f=1;  
        return;
    }
    int mid=(l+r)>>1;
    build(root*2,l,mid);
    build(root*2+1,mid+1,r);
    t[root].f=t[root*2].f + t[root*2+1].f;
}
void update(int root,int p)
{
    int l=t[root].l,r=t[root].r;
    if(l==r)
    {
        t[root].f = !t[root].f;
        return;
    }
    int mid = (l+r)>>1;
    if(p<=mid)
    update(root*2,p);
    else if(p>mid)
    update(root*2+1,p);
    t[root].f = t[root*2].f + t[root*2+1].f;
}
int query(int root,int ql,int qr)
{
    int l=t[root].l,r=t[root].r;
    if(ql>r||qr<l)return 0;
    if(ql<=l&&qr>=r)
    {
        return t[root].f;
    }
    int mid = (l+r)>>1;
    if(qr<=mid)
    return query(root*2,ql,qr);
    else if(ql>mid)
    return query(root*2+1,ql,qr);
    else
    {
        return query(root*2,ql,qr) + query(root*2+1,ql,qr);
    }
}
void dfs(int u,int fa)
{
    p1[u]=++index;
    con[u]=index;
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        int v=e[i].v;
        if(v==fa)continue;
        dfs(v,u);
    }
    p2[u]=index;
}
int main()
{
    int n,u,v;
    while(~scanf("%d",&n))
    {
        memset(head,-1,sizeof(head));
        tot=0;
        for(int i=1;i<=n-1;i++)
        {
            scanf("%d%d",&u,&v);
            add(u,v);
            add(v,u);
        }
        dfs(1,-1);
        build(1,1,n);
        char op[5];
        int m;
        scanf("%d",&m);
        for(int i=1;i<=m;i++)
        {
            scanf("%s%d",op,&u);
            if(op[0]=='Q')
            {
                printf("%d\n",query(1,p1[u],p2[u]));
            }
            else
            {
                update(1,con[u]);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值