洛谷P3459 [POI2007]MEG-Megalopolis——题解

题目传送门
题目大意:
题目翻译有毒,我也表述不清楚,可以看第一篇题解弄清题意。


思考过程&具体做法:
我是用树链剖分硬搞的。具体的是把每个点父亲连向自己的那条边作为自己的权值,土路为1,公路为0,这样除了1外一开始所有点点权都是1,树链剖分维护点权即可。


代码:

#include <bits/stdc++.h>
using namespace std;

const int maxn=2.5e5+1000;
struct stu
{
    int to,next;
}road[maxn*2]; int first[maxn],cnt=0;
int seg[maxn*5],dep[maxn],cnum[maxn],fa[maxn],hson[maxn],top[maxn],id[maxn],dfn[maxn];
int n,m,nowtop;

void addedge(int x,int y)
{
    road[++cnt].to=y;
    road[cnt].next=first[x];
    first[x]=cnt;
}

void dfs1(int now,int depth)
{
    dep[now]=depth;
    cnum[now]=1;
    int maxx=0;
    for(int i=first[now];i;i=road[i].next)
    {
        int to=road[i].to;
        if(to==fa[now]) continue;
        fa[to]=now;
        dfs1(to,depth+1);
        cnum[now]+=cnum[to];
        if(cnum[to]>maxx)
        {
            maxx+=cnum[to];
            hson[now]=to;
        }
    }
}

void dfs2(int now,int what)
{
    if(what==1) nowtop=now;
    top[now]=nowtop;
    id[now]=++cnt;
    dfn[cnt]=now;
    if(!hson[now]) return;
    dfs2(hson[now],0);
    for(int i=first[now];i;i=road[i].next)
    {
        int to=road[i].to;
        if(to==fa[now]||to==hson[now]) continue;
        dfs2(to,1);
    }
}

void build(int note,int l,int r)
{
    if(l==r)
    {
        if(l==1) seg[note]=0;
        else seg[note]=1;
        return;
    }
    int mid=(l+r)>>1;
    build(note*2,l,mid);
    build(note*2+1,mid+1,r);
    seg[note]=seg[note*2]+seg[note*2+1];
}

void change(int note,int l,int r,int want)
{
    if(l==r) { seg[note]=0;return; }
    int mid=(l+r)>>1;
    if(want<=mid) change(note*2,l,mid,want);
    else change(note*2+1,mid+1,r,want);
    seg[note]=seg[note*2]+seg[note*2+1];
}

int query(int note,int l,int r,int wantl,int wantr)
{
    if(l>wantr||r<wantl) return 0;
    if(l>=wantl&&r<=wantr) return seg[note];
    int mid=(l+r)>>1;
    return query(note*2,l,mid,wantl,wantr)+query(note*2+1,mid+1,r,wantl,wantr);
}

int ask(int x)
{
    int nowans=0;
    while(top[x]!=1)
    {
        nowans+=query(1,1,n,id[top[x]],id[x]);
        x=fa[top[x]];
    }
    nowans+=query(1,1,n,id[1],id[x]);
    return nowans;
}

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n-1;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        if(x>y) swap(x,y);
        addedge(x,y);
    }
    dfs1(1,1);
    cnt=0;
    dfs2(1,1);
    build(1,1,n);
    scanf("%d",&m);
    char s[100];
    for(int i=1;i<=m+n-1;i++)
    {
        scanf("%s",s);
        if(s[0]=='A')
        {
            int x,y;
            scanf("%d%d",&x,&y);
            change(1,1,n,id[y]);
        }
        else
        {
            int x;
            scanf("%d",&x);
            printf("%d\n",ask(x));
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39662197/article/details/80343746
今日推荐