ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

树上分治

2019-09-02 15:39:54  阅读:221  来源: 互联网

标签:选点 node int 分治 树上 root


在树上进行分治的时候常常会选取一个点,通过该点将树分隔成为多个分支,在多个分支中进行分治,最终回到该点上处理各个分治之间的关系。

分治的关键步骤大概是:选点,分治,合并。

选点:

树上分治的关键在于,通过分治可以将树编程许多小的分支,从而化简时间复杂度,然而为了使平均时间最小,我们通常会对每一个子树进行预处理,获取该树的重心位置,从而已该点为划分,将树分成各个小的子模块。

树的重心:https://blog.csdn.net/qq_38890926/article/details/81222698

总的代码:

struct node
{
    int to;
    int v;
    int next;
};
int tot;
int head[maxn];
node e[maxn<<2];
void add(int f,int t,int v)
{
    e[tot].to=t;
    e[tot].v=v;
    e[tot].next=head[f];
    head[f]=tot;
    tot++;
}
void init()
{
    tot=0;
    memset(head,-1,sizeof(head));
}

struct TreeDC
{
    bool vis[maxn];
    int sum[maxn],smax; //记录的子树规模,最大字数规模
    int scale,root;  // 遍历的子树规模,子树重心

    inline void init(){memset(vis,0,sizeof(vis));initsubtree(n);}
    inline void initsubtree(int sc){scale=sc;root=0;smax=inf;}


    void dfs(int rt,int fa)
    {
        for(int i=head[rt];i!=-1;i=e[i].next)
        {
            int to=e[i].to;
            if(to==fa||vis[to]==true)continue;
            dfs(to,rt);
        }
    }
    void solve(int rt)
    {
        for(int i=head[rt];i!=-1;i=e[i].next)
        {
            int to=e[i].to;
            if(vis[to]==true)continue;
            dfs(to,rt);
        }
    }
    void dc(int rt)
    {
        vis[rt]=1;
        solve(rt);
        for(int i=head[rt];i!=-1;i=e[i].next)
        {
            int to=e[i].to;
            if(vis[to]==true)continue;
            initsubtree(sum[to]);
            centre(to,-1);
            dc(root);
        }
    }
    void centre(int rt,int fa)
    {
        sum[rt]=1;
        int rtmax=0;
        for(int i=head[rt];i!=-1;i=e[i].next)
        {
            int to=e[i].to;
            if(to==fa||vis[to]==true)continue;
            centre(to,rt);
            sum[rt]=sum[rt]+sum[to];
            rtmax=max(rtmax,sum[to]);
        }
        rtmax=max(rtmax,scale-sum[rt]);
        if(smax>rtmax)root=rt,smax=rtmax;
    }
    void getans()
    {
        init();
        centre(1,-1);
        dc(root);
    }
}tr;

 

标签:选点,node,int,分治,树上,root
来源: https://blog.csdn.net/qq_38890926/article/details/81258623

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有