bzoj 1103 大都市meg (dfs序+线段树)

题意:

       一颗树,每条边权是1,两种操作,一种查询x到根的距离,一种把某边改为0

思路:

        对于一个边变了,那么影响的就是子树,所以dfs序+线段树就行了,这题对于时间要求很低,vector存边,每次暴力找答案也能A

错误及反思:

代码:

#include<bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int N = 260000;
int segtree[N<<2],lazy[N<<2];
vector<int> e[N];
int id[N],to[N],len[N],fa[N];
int n,tid,w;

void dfs(int now,int f,int val){
    id[now]=++tid;
    fa[now]=f;
    len[tid]=val;
    for(int i=0;i<e[now].size();i++){
        if(e[now][i]!=f)
            dfs(e[now][i],now,val+1);
    }
    to[now]=tid;
}

void build(int l,int r,int rt){
    if(l==r){
        segtree[rt]=len[l];
        return ;
    }
    int m=l+r>>1;
    build(lson); build(rson);
}

void pushdown(int rt){
    if(lazy[rt]!=0){
        segtree[rt<<1|1]+=lazy[rt];
        segtree[rt<<1]+=lazy[rt];
        lazy[rt<<1]+=lazy[rt];
        lazy[rt<<1|1]+=lazy[rt];
        lazy[rt]=0;
    }
}
void update(int L,int R,int l,int r,int rt){
    if(L<=l&&R>=r){
        lazy[rt]--;
        segtree[rt]--;
        return ;
    }
    pushdown(rt);
    int m=l+r>>1;
    if(L<=m) update(L,R,lson);
    if(R>m) update(L,R,rson);
    return ;
}

int query(int x,int l,int r,int rt){
    if(l==r) return segtree[rt];
    pushdown(rt);
    int m=l+r>>1;
    if(x<=m) return query(x,lson);
    return query(x,rson);
}

int main(){
    scanf("%d",&n);
    for(int i=0,u,v;i<n-1;i++){
        scanf("%d%d",&u,&v);
        e[u].push_back(v);
        e[v].push_back(u);
    }
    dfs(1,1,0);
    build(1,n,1);
    scanf("%d",&w);
    while(w){
        char t[10]; scanf("%s",t);
        if(t[0]=='W'){
            w--;
            int x; scanf("%d",&x);
            printf("%d\n",query(id[x],1,n,1));
        }
        else{
            int x,y;
            scanf("%d%d",&x,&y);
            if(fa[y]==x) swap(x,y);
            update(id[x],to[x],1,n,1);
        }

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值