BZOJ1086 [SCOI2005]王室联邦(洛谷P2325)

292 篇文章 1 订阅
281 篇文章 1 订阅

DFS

BZOJ题目传送门
洛谷题目传送门

这道题就是教你怎么树分块的。

开一个栈存当前经过的所有点中未编号的点,DFS一遍。当回溯到 x x 发现点的数量 B B 时,就新建一个省,省会为x x x 不属于该省,并把这之间的点都归到x里。遍历完 x x 的子树后把x放入栈中。DFS完后把剩下在栈里的归到最后一个省里去即可。

代码:

#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1001
#define F inline
using namespace std;
struct edge{int next,to; }ed[N<<1];
int n,b,tp,k,p,h[N],stk[N],num[N],rt[N];
F char readc(){
    static char buf[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    if (l==r) return EOF; return *l++;
}
F int _read(){
    int x=0; char ch=readc();
    while (!isdigit(ch)) ch=readc();
    while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
    return x;
}
F void writec(int x){ if (x>9) writec(x/10); putchar(x%10+48); }
#define addedge(x,y) (ed[++k]=(edge){h[x],y},h[x]=k)
void dfs(int x,int fa){
    int now=tp;
    for (int i=h[x],v;i;i=ed[i].next)
        if ((v=ed[i].to)!=fa){
            dfs(v,x);
            if (tp-now>=b){
                rt[++p]=x;
                while (tp!=now) num[stk[tp--]]=p; 
            }
        }
    stk[++tp]=x;
}
int main(){
    n=_read(),b=_read();
    for (int i=1,x,y;i<n;i++)
        x=_read(),y=_read(),addedge(x,y),addedge(y,x);
    dfs(1,0),writec(p),putchar('\n');
    while (tp) num[stk[tp--]]=p;
    for (int i=1;i<=n;i++)
        writec(num[i]),putchar(' ');
    putchar('\n');
    for (int i=1;i<=p;i++)
        writec(rt[i]),putchar(' ');
    return putchar('\n'),0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值