树分块学习笔记

· · 个人记录

通过dfs把子树中大于 B 的分为一组,剩余的(肯定小于 B )上传分到父亲那组。由于父亲那组大于 B ,加进去小于 3B 。 B 的大小会影响空间和时间的优劣,需要根据题目给定的时间和空间,时间多空间小就 B 大,空间多时间少就 B 小。从而来决定 B 的大小。

<!--more-->

真正的树分块大概是topologycal cluster partition。

#include <bits/stdc++.h>
using namespace std;

inline int read()
{
    int x=0; int f=1; char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-')f=-1; ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0'; ch=getchar();}
    return x*f;
}

const int MAXN = 10005;
std::vector<int> G[MAXN];
int root[MAXN],bl[MAXN],stk[MAXN];
int n,B,top,tot,cnt;

inline void addedge(int u,int v)
{
    G[u].push_back(v);
    G[v].push_back(u);
}

void dfs(int x,int fa)
{
    int bot=top,sz=G[x].size();
    for (int i = 0; i < sz; ++i)
    {
        int y=G[x][i];
        if(y==fa) continue;
        dfs(y,x);
        if(top-bot>=B)
        {
            root[++cnt]=x;
            while(top!=bot)
                bl[stk[top--]]=cnt;
        }
    }
    stk[++top]=x;
}

int main(int argc, char const *argv[])
{
    n=read(); B=read();
    for(int i=1; i<n; i++)
        addedge(read(),read());
    dfs(1,0);
    while(top) bl[stk[top--]]=cnt;
    printf("%d\n",cnt);
    for(int i=1; i<=n; i++)
        printf("%d ",bl[i]);
    puts("");
    for(int i=1; i<=cnt; i++)
        printf("%d ",root[i]);
    return 0;
}