BZOJ 1086 王室联邦 [王室联邦-树上分块]

这是一种特殊的分块方法,具体情况我论文中有讲述。
建议大家寻常的树上分块可以使用这种分块方法,不容易被卡

#include<bits/stdc++.h>
using namespace std;
const int N = 10000;
inline void read(int &res){
    static char ch;int flag=1;
    while((ch=getchar())<'0'||ch>'9')if(ch=='-')flag=-1;res=ch-48;
    while((ch=getchar())>='0'&&ch<='9')res=res*10+ch-48;res*=flag;
}
int n,m,cnt,top,pro;
int last[N],q[N],sz[N],sum[N],belong[N];
struct data{int to,next;}E[2005];
void insert(int u,int v){
    E[++cnt].to=v;E[cnt].next=last[u];last[u]=cnt;
    E[++cnt].to=u;E[cnt].next=last[v];last[v]=cnt;
}
void dfs(int x,int fa){
    q[++top]=x;
    for(int i=last[x];i;i=E[i].next)if(E[i].to!=fa){
        dfs(E[i].to,x);
        if(sz[x]+sz[E[i].to]>=m){
            sz[x]=0;
            sum[++pro]=x;
            while(q[top]!=x)
                belong[q[top--]]=pro;
        }else sz[x]+=sz[E[i].to];
    }
    sz[x]++;
}
void paint(int x,int fa,int c){
    if(belong[x])c=belong[x];
    else belong[x]=c;
    for(int i=last[x];i;i=E[i].next)
        if(E[i].to!=fa)
            paint(E[i].to,x,c);
}
int main() 
{
    read(n),read(m);
    if(n<m){
        puts("0");return 0;
    }
    for(register int u,v,i=1;i<n;i++)
        read(u),read(v),insert(u,v);
    dfs(1,0);
    if(!pro)sum[++pro]=1;
    paint(1,0,pro);
    printf("%d\n",pro);
    for(register int i=1;i<=n;i++)printf("%d ",belong[i]);
    printf("\n");
    for(register int i=1;i<=pro;i++)printf("%d ",sum[i]);
    printf("\n");
    return 0;
}

这里写图片描述

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值