zoukankan      html  css  js  c++  java
  • P3258 松鼠的新家

    松鼠的新家

    洛谷链接

    尽管标签是省选/NOI-,但提交的通过率已经高到三分之一了。

    但它仍旧是一个省选/NOI-的题。

    大致题意就是按输入的顺序走一棵树,看每个节点经过多少次。问题就相当于把一条链上的所有节点权值都加一,最后统计每个点的权值。

    但这样的时间复杂度比较高,所以我们可以把这条链的头节点和尾节点的权值都加一,然后把它们的LCA减一,它们LCA的父亲节点减一。之后每次通记每个节点都统计该节点及其子树的权值和,就是这个节点被经过的次数。

    而题目要求在最后的终点不需要计算,所以我们可以把“这条链的头节点和尾节点的权值都加一”,改为“这条链的尾节点的父亲和头节点的权值都加一”,就可以实现题目要求。

     1 #include<cstdio>
     2 #include<iostream>
     3 #define N 300010
     4 using namespace std;
     5 int next[N*2],to[N*2],num,head[N],ans[N],size[N],father[N],top[N],sum[N],n,a,b,c,deep[N],haha[N];
     6 void add(int false_from,int false_to){
     7     next[++num]=head[false_from];
     8     to[num]=false_to;
     9     head[false_from]=num;
    10 }
    11 void dfs1(int x){
    12     size[x]=1;
    13     deep[x]=deep[father[x]]+1;
    14     for(int i=head[x];i;i=next[i])
    15         if(father[x]!=to[i]){
    16             father[to[i]]=x;
    17             dfs1(to[i]);
    18             size[x]+=size[to[i]];
    19         }
    20 }
    21 void dfs2(int x){
    22     int mmax=0;
    23     if(!top[x])
    24         top[x]=x;
    25     for(int i=head[x];i;i=next[i])
    26         if(father[x]!=to[i]&&size[to[i]]>size[mmax])
    27             mmax=to[i];
    28     if(mmax){
    29         top[mmax]=top[x];
    30         dfs2(mmax);
    31     }
    32     for(int i=head[x];i;i=next[i])
    33         if(father[x]!=to[i]&&to[i]!=mmax)
    34             dfs2(to[i]);
    35 }
    36 void dfs3(int x){
    37     ans[x]=sum[x];
    38     for(int i=head[x];i;i=next[i])
    39         if(father[x]!=to[i]){
    40             dfs3(to[i]);
    41             ans[x]+=ans[to[i]];
    42         }
    43 }
    44 int lca(int x,int y){
    45     while(top[x]!=top[y]){
    46         if(deep[top[x]]<deep[top[y]])
    47             swap(x,y);
    48         x=father[top[x]];
    49     }
    50     if(deep[x]<deep[y])
    51         return x;
    52     return y;
    53 }
    54 int main(){
    55     scanf("%d",&n);
    56     for(int i=1;i<=n;++i)
    57         scanf("%d",&haha[i]);
    58     for(int i=1;i<n;++i){
    59         scanf("%d%d",&a,&b);
    60         add(a,b);
    61         add(b,a);
    62     }
    63     dfs1(1);
    64     dfs2(1);
    65     for(int i=1;i<n;++i){
    66         a=haha[i];
    67         b=haha[i+1];
    68         c=lca(a,b);
    69         sum[a]++;
    70         sum[father[b]]++;
    71         sum[c]--;
    72         sum[father[c]]--;
    73     }
    74     dfs3(1);
    75     for(int i=1;i<=n;++i)
    76         printf("%d
    ",ans[i]);
    77     return 0;
    78 }
    View Code

     

  • 相关阅读:
    redis 误删dump.rdb 解决方案
    Redis 初级应用
    .net core 依赖注入
    Android 基础总结
    hander用法笔记
    百万条数据快速查询优化技巧参考(优化并不是绝对,具体得根据业务实际情况)
    网站收藏
    自定义MVC HtmlHelpe之分页
    asp.net 页面请求原理
    Two Sum
  • 原文地址:https://www.cnblogs.com/jsawz/p/6817244.html
Copyright © 2011-2022 走看看