BZOJ1086:[SCOI2005]王室联邦——题解

http://www.lydsy.com/JudgeOnline/problem.php?id=1086

题面源于洛谷。

题目描述

“余”人国的国王想重新编制他的国家。他想把他的国家划分成若干个省,每个省都由他们王室联邦的一个成员来管理。

他的国家有n个城市,编号为1..n。一些城市之间有道路相连,任意两个不同的城市之间有且仅有一条直接或间接的道路。为了防止管理太过分散,每个省至少要有B个城市,为了能有效的管理,每个省最多只有3B个城市。

每个省必须有一个省会,这个省会可以位于省内,也可以在该省外。但是该省的任意一个城市到达省会所经过的道路上的城市(除了最后一个城市,即该省省会)都必须属于该省。

一个城市可以作为多个省的省会。

聪明的你快帮帮这个国王吧!

输入输出格式

输入格式:

第一行包含两个数N,B(1<=N<=1000, 1 <= B <= N)。接下来N-1行,每行描述一条边,包含两个数,即这条边连接的两个城市的编号。

输出格式:

如果无法满足国王的要求,输出0。否则第一行输出数K,表示你给出的划分方案中省的个数,编号为1..K。第二行输出N个数,第I个数表示编号为I的城市属于的省的编号,第三行输出K个数,表示这K个省的省会的城市编号,如果有多种方案,你可以输出任意一种。

输入输出样例

输入样例#1: 
8 2 
1 2 
2 3 
1 8 
8 7 
8 6 
4 6 
6 5 
输出样例#1: 
3 
2 1 1 3 3 3 3 2 
2 1 8 

——————————————————————————————————————————-

欢迎访问小兔大佬的博客:http://www.cnblogs.com/RabbitHu/p/BZOJ1086.html

由神奇的证明得知:不存在为0的情况(貌似肉眼观察法蛮容易得出)

我们一个dfs搜下去,搜到一个子树>=b就是一个省了,那么省会可以设为这个子树的根。

最后把栈中的点加入最后一个省即可,又有神奇的证明发现这样的话大小一定<=3b。

……证明不会……

#include<cstdio>
#include<stack>
#include<cctype>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1001;
const int BIG=1000001;
const int M=200001;
const int INF=2147483647;
inline int read(){
    int X=0,w=0;char ch=0;
    while(!isdigit(ch)){w|=ch=='-';ch=getchar();}
    while(isdigit(ch))X=(X<<3)+(X<<1)+(ch^48),ch=getchar();
    return w?-X:X;
}
struct node{
    int to;
    int nxt;
}edge[N*2];
int n,b,cnt,head[N];
int top,idx,stk[N],blk[N],cap[N];
inline void add(int u,int v){
    cnt++;
    edge[cnt].to=v;
    edge[cnt].nxt=head[u];
    head[u]=cnt;
    return;
}
void dfs(int u,int f){
    int st=top;
    for(int i=head[u];i;i=edge[i].nxt){
    int v=edge[i].to;
    if(v==f)continue;
    dfs(v,u);
    if(top-st>=b){
        cap[++idx]=u;
        while(top>st)blk[stk[top--]]=idx;
    }
    }
    stk[++top]=u;
    return;
}
int main(){
    n=read();
    b=read();
    for(int i=1;i<n;i++){
    int u=read(),v=read();
    add(u,v);add(v,u);
    }
    dfs(1,0);
    while(top)blk[stk[top--]]=idx;
    printf("%d\n",idx);
    for(int i=1;i<=n;i++){
    printf("%d ",blk[i]);
    }
    putchar('\n');
    for(int i=1;i<=idx;i++){
    printf("%d ",cap[i]);
    }
    putchar('\n');
    return 0;
}

 

posted @ 2018-01-03 16:17  luyouqi233  阅读(297)  评论(0编辑  收藏  举报