洛谷:P3258树上点差分

题目链接
题解:

难点在于根据访问顺序推出差分方式,前置知识:LCA+树上点差分

AC代码:

#include<bits/stdc++.h>
using namespace std ;
const int maxn=3e5+5;
struct node
{
    int to,nex;

} tr[maxn*4];
int pre[maxn][32],depth[maxn],head[maxn],ord[maxn];
int point[maxn];
//树上倍增lca
int n,m,cnt,ans;
void add(int u,int v)
{
    tr[cnt].to=v;
    tr[cnt].nex=head[u];
    head[u]=cnt++;
}
void dfs(int u,int fa)//求深度
{
    depth[u]=depth[fa]+1;
    pre[u][0]=fa;
    for(int i=1; (1<<i)<=depth[u]; i++)
        pre[u][i]=pre[pre[u][i-1]][i-1];
    for(int i=head[u]; ~i; i=tr[i].nex)
    {
        int v=tr[i].to;
        if(fa!=v)
        {
            dfs(v,u);
        }
    }
}
int lca(int u,int v)
{
    if(depth[u]<depth[v])
        swap(u,v);//让u的深度大
    int i=-1,j;
    while((1<<(i+1))<=depth[u])//从u跨到根节点的跨度
        i++;
    for(j=i; j>=0; j--) //同一水平
    {
        if(depth[u]-(1<<j)>=depth[v])
        {
            u=pre[u][j];
        }
    }
    if(u==v)
    {
        return u;
    }
    for(j=i; j>=0; j--)
    {
        if(pre[u][j]!=pre[v][j])
        {
            u=pre[u][j];
            v=pre[v][j];
        }
    }
    return pre[u][0];
}
//树上差分
void dfs_(int u,int fa)
{ //printf("%d\n",point[u]);
    for(int i=head[u];~i;i=tr[i].nex)
    {
        int v=tr[i].to;
        if(v==fa)
            continue;
         dfs_(v,u);
         point[u]+=point[v];
    }
    //ans=max(ans,point[u]);
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&ord[i]);
    memset(head,-1,sizeof(head));
    int u,v;
    for(int i=1; i<n; i++)
    {
        scanf("%d %d",&u,&v);
        add(u,v);
        add(v,u);
    }
    dfs(1,0);
    for(int i=1;i<n;i++)
    {

        int lc=lca(ord[i],ord[i+1]);
        //printf("%d\n",lc);
        point[ord[i]]++;
        point[pre[ord[i+1]][0]]++;
        point[lc]--;
        if(pre[lc][0]!=0)
        point[pre[lc][0]]--;
    }
    dfs_(1,0);
    //printf("%d",point[ord[1]]);
    for(int i=1;i<=n;i++)
    {
            printf("%d\n",point[i]);
    }
}
发布了205 篇原创文章 · 获赞 12 · 访问量 8493

猜你喜欢

转载自blog.csdn.net/yangzijiangac/article/details/104046662
今日推荐