3668: [Noi2014]起床困难综合症

遇上水题,好爽啊。

就将每一二进制位初始为0与1的最终情况暴力求出来,贪心一下就好了。

code:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
struct trnode{
    int dep,fa,top,son,tot,l,r,lc,rc,c,u;
}tr[600020];int ys[300010],s[300010],z=0,trlen=0;
int ans[300010];
struct node{
    int y,next;
}a[600010];int len=0,last[300010];
int b[300010];
void ins(int x,int y)
{
    a[++len].y=y;
    a[len].next=last[x];last[x]=len;
}
int bt(int l,int r)
{
    int x=++trlen;
    tr[x].l=l;tr[x].r=r;tr[x].c=0;
    tr[x].u=0;
    if(l!=r)
    {
        int mid=(l+r)/2;
        tr[x].lc=bt(l,mid);
        tr[x].rc=bt(mid+1,r);
    }
    return x;
}
void update(int x)
{
    int lc=tr[x].lc,rc=tr[x].rc;
    tr[lc].c+=tr[x].c;tr[rc].c+=tr[x].c;
    tr[x].c=0;
}
void change(int x,int l,int r)
{
    if(tr[x].l==l&&tr[x].r==r)
    {
        tr[x].c+=1;
        return;
    }
    if(tr[x].c!=0) update(x);
    int mid=(tr[x].l+tr[x].r)/2,lc=tr[x].lc,rc=tr[x].rc;
    if(r<=mid) change(lc,l,r);
    else if(l>mid) change(rc,l,r);
    else change(lc,l,mid),change(rc,mid+1,r);
}
void pre_node(int x,int fa)
{
    tr[x].fa=fa;tr[x].dep=tr[fa].dep+1;tr[x].tot=1;
    for(int i=last[x];i;i=a[i].next)
    {
        int y=a[i].y;
        if(y==fa) continue;
        pre_node(y,x);tr[x].tot+=tr[y].tot;
        if(tr[tr[x].son].tot<tr[y].tot) tr[x].son=y;
    }
}
void pre_edge(int x,int top)
{
    ys[x]=++z;s[z]=x;tr[x].top=top;
    if(tr[x].son!=0) pre_edge(tr[x].son,top);
    for(int i=last[x];i;i=a[i].next)
    {
        int y=a[i].y;
        if(y==tr[x].fa||y==tr[x].son) continue;
        pre_edge(y,y);
    }
}
void solve(int x,int y)
{
    int tx=tr[x].top,ty=tr[y].top;
    while(tx!=ty)
    {
        if(tr[tx].dep<tr[ty].dep) swap(x,y),swap(tx,ty);
        change(1,ys[tx],ys[x]);
        x=tr[tx].fa;tx=tr[x].top;
    }
    if(tr[x].dep<tr[y].dep) swap(x,y);
    change(1,ys[y],ys[x]);
}
void print(int x)
{
    if(tr[x].l==tr[x].r) ans[s[tr[x].l]]=tr[x].c;
    else update(x),print(tr[x].lc),print(tr[x].rc);
}
int main()
{
    int n;scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d",&b[i]);
    for(int i=1;i<n;i++)
    {
        int x,y;scanf("%d %d",&x,&y);
        ins(x,y);ins(y,x);
    }
    z=0;pre_node(1,0);pre_edge(1,1);bt(1,n);
    for(int i=2;i<=n;i++) solve(b[i-1],b[i]);
    print(1);
    for(int i=1;i<=n;i++)
    {
        if(i!=b[1]) ans[i]--;
        printf("%d\n",ans[i]);
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值