zoukankan      html  css  js  c++  java
  • Split The Tree(dfs序+树状数组)

    Split The Tree

    时间限制: 1 Sec  内存限制: 128 MB
    提交: 46  解决: 11
    [提交] [状态] [讨论版] [命题人:admin]

    题目描述

    You are given a tree with n vertices, numbered from 1 to n. ith vertex has a value wi
    We define the weight of a tree as the number of different vertex value in the tree.
    If we delete one edge in the tree, the tree will split into two trees. The score is the sum of these two trees’ weights.
    We want the know the maximal score we can get if we delete the edge optimally.

    输入

    Input is given from Standard Input in the following format:
    n
    p2 p3  . . . pn
    w1 w2  . . . wn
    Constraints
    2 ≤ n ≤ 100000 ,1 ≤ pi < i
    1 ≤ wi ≤ 100000(1 ≤ i ≤ n), and they are integers
    pi means there is a edge between pi and i

    输出

    Print one number denotes the maximal score.

    样例输入

    3
    1 1
    1 2 2
    

    样例输出

    3
    

     思路:

    把序列延长一倍,每段子树的两边的区间连起来,将问题转化成维护区间中不同数字个数的最大值。

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn=2e5+10;
    vector<pair<int,int> >vi[maxn];
    int tree[maxn];
    inline int lowbit(int x){return x&-x;}
    void update(int x,int val) {for (int i=x; i<maxn; i+=lowbit(i)) tree[i]+=val;}
    int Query(int x){int res=0;for (int i=x; i; i-=lowbit(i)) res+=tree[i]; return res;}
    int st[maxn],dfn[maxn],ed[maxn],tot=0;
    struct Edge{int u,v,next;}e[maxn];
    int head[maxn],cnt=0;
    inline void add(int u,int v){e[cnt]=Edge{u,v,head[u]};head[u]=cnt++;}
    int n,vis[maxn],w[maxn];
    void dfs(int x,int fa=0){
        st[x]=++tot;
        dfn[tot]=x;
        dfn[n+tot]=x;
        for (int v,i=head[x]; ~i; i=e[i].next){
            v=e[i].v;
            if(v==fa) continue;
            dfs(v,x);
        }
        ed[x]=tot;
    }
    int ans[maxn],res=0;
    int main(){
        memset(head,-1,sizeof(head));
        scanf("%d",&n);
        for (int p,i=2; i<=n; i++) scanf("%d",&p),add(p,i),add(i,p);
        for (int i=1; i<=n; i++) scanf("%d",&w[i]);
        dfs(1);
        vi[ed[1]].push_back({st[1],1});
        for (int i=2; i<=n; i++){
            vi[ed[i]].push_back({st[i],i});
            vi[st[i]-1+n].push_back({ed[i]+1,i});
        }
        for (int i=1; i<=n+n; i++){
            if(vis[w[dfn[i]]]) update(vis[w[dfn[i]]],-1);
            update(i,1);
            vis[w[dfn[i]]]=i;
            for (auto u:vi[i])
                ans[u.second]+=Query(i)-Query(u.first-1);
        }
        for (int i=1; i<=n; i++) res=max(res,ans[i]);
        printf("%d
    ",res);
        return 0;
    }
    View Code
  • 相关阅读:
    sourcenav安装
    vim-addon-manager【转】
    zmq重点
    一个简单的解决方法:word文档打不开,错误提示mso.dll模块错误。
    微软验证码项目 Captcha Code Demo 从 .NET Core 1.1.2升级到2.1.0
    海康设备如何接入萤石开放平台
    ABP 启用多租户实现数据隔离
    Docker 开发者常用操作命令
    .NET Core 深度克隆对象,引用类型的平行世界
    详解 .NET Core 遍历 List 并移除项
  • 原文地址:https://www.cnblogs.com/acerkoo/p/9593896.html
Copyright © 2011-2022 走看看