樹上分治

在樹上進行分治的時候常常會選取一個點,通過該點將樹分隔成爲多個分支,在多個分支中進行分治,最終回到該點上處理各個分治之間的關係。

分治的關鍵步驟大概是:選點,分治,合併。

選點:

樹上分治的關鍵在於,通過分治可以將樹編程許多小的分支,從而化簡時間複雜度,然而爲了使平均時間最小,我們通常會對每一個子樹進行預處理,獲取該樹的重心位置,從而已該點爲劃分,將樹分成各個小的子模塊。

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

 

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