树上分治

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

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

选点:

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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值