P3258 [JLOI2014] 松鼠的新家

原题链接

题解

1.小模拟+树上差分+lca

code

#include<bits/stdc++.h>
using namespace std;
int a[300006]={0};
vector<int> G[300005];
int depth[500005]={0};
int fa[500005][30]={0};
int tree[500005]={0};
void dfs(int now,int pre)
{
    fa[now][0]=pre;
    depth[now]=depth[pre]+1;
    for(auto next:G[now])
    {
        if(next==pre) continue;
        dfs(next,now);
    }
}
int n;
void init()
{
    for(int k=1;k<=22;k++)
    {
        for(int i=1;i<=n;i++)
        {
            fa[i][k]=fa[fa[i][k-1]][k-1];
        }
    }
}

int lca(int x,int y)
{
    if(depth[x]<depth[y]) swap(x,y);
    for(int i=22;i>=0;i--) if(depth[fa[x][i]]>=depth[y]) x=fa[x][i];
    if(x==y) return x;
    for(int i=22;i>=0;i--)
    {
        if(fa[x][i]!=fa[y][i])
        {
            x=fa[x][i];
            y=fa[y][i];
        }
    }
    return fa[x][0];
}



void cal(int now,int pre)
{
    for(auto next:G[now])
    {
        if(next==pre) continue;
        cal(next,now);
        tree[now]+=tree[next];
    }
}

int main()
{
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    for(int i=1;i<n;i++)
    {
        int x,y;
        cin>>x>>y;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    dfs(1,0);
    init();

    for(int i=2;i<=n;i++)
    {
        int x=a[i-1],y=a[i];

        tree[x]++;
        tree[fa[y][0]]++;
        int f=lca(x,y);
        tree[f]--;
        tree[fa[f][0]]--;
    }

    cal(1,0);
    for(int i=1;i<=n;i++) cout<<tree[i]<<endl;
    return 0;
}

posted @   纯粹的  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示