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;
}
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号