BZOJ 1086: [SCOI2005]王室联邦

维护一个栈,从任意一个节点开始 dfs,在回溯时加入到栈中。
dfs每一个子树之后,若相对于刚进入该节点时栈的大小,新增加的节点超过 B,就将它们分为一块
这样分完保证不超过 2B,而整个dfs结束之后,若栈中还有节点,就把它们归为最后一块

#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define pii pair<int, int>
#define lp p << 1
#define rp p << 1 | 1
#define mid ((l + r) >> 1)
#define ll long long
#define db double
#define rep(i,a,b) for(int i=a;i<b;i++)
#define per(i,a,b) for(int i=b-1;i>=a;i--)
#define Edg int ccnt=1,head[N],to[N*2],ne[N*2];void addd(int u,int v){to[++ccnt]=v;ne[ccnt]=head[u];head[u]=ccnt;}void add(int u,int v){addd(u,v);addd(v,u);}
#define Edgc int ccnt=1,head[N],to[N*2],ne[N*2],c[N*2];void addd(int u,int v,int w){to[++ccnt]=v;ne[ccnt]=head[u];c[ccnt]=w;head[u]=ccnt;}void add(int u,int v,int w){addd(u,v,w);addd(v,u,w);}
#define es(u,i,v) for(int i=head[u],v=to[i];i;i=ne[i],v=to[i])
const int MOD = 1e9 + 7;
void M(int &x){if(x>=MOD)x-=MOD;if(x<0)x+=MOD;}
int qp(int a,int b=MOD-2){int ans=1;for(;b;a=1LL*a*a%MOD,b>>=1)if(b&1)ans=1LL*ans*a%MOD;return ans%MOD;}

char buf[1 << 21], *p1 = buf, *p2 = buf;
inline char getc() {
    return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++;
}
inline int _() {
    int x = 0, f = 1; char ch = getc();
    while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getc(); }
    while (ch >= '0' && ch <= '9') { x = x * 10ll + ch - 48; ch = getc(); }
    return x * f;
}
const int N = 1111;
Edg
int n, b, st[N], top, belong[N], province[N], cnt;

void dfs(int u, int f) {
    int cur = top;
    es (u, i, v) {
        if (v == f) continue;
        dfs(v, u);
        if (top - cur >= b) {
            province[++cnt] = u;
            while (top != cur) belong[st[top--]] = cnt;
        }
    }
    st[++top] = u;
}

int main() {
    n = _(), b = _();
    rep (i, 1, n) {
        int u = _(), v = _();
        add(u, v);
    }
    dfs(1, 0);
    while (top) belong[st[top--]] = cnt;
    printf("%d\n", cnt);
    rep (i, 1, n + 1) printf("%d%c", belong[i], " \n"[i == n]);
    rep (i, 1, cnt + 1) printf("%d%c", province[i], " \n"[i == cnt]);
    return 0;
}
上一篇:Docker 03 镜像命令


下一篇:Error: rendered manifests contain a resource that already exists.