树上分治

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

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

选点:

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

树的重心: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;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章