• [BZOJ1086][SCOI2005]王室联邦


    [BZOJ1086][SCOI2005]王室联邦

    试题描述

    “余”人国的国王想重新编制他的国家。他想把他的国家划分成若干个省,每个省都由他们王室联邦的一个成员来管理。他的国家有n个城市,编号为1..n。一些城市之间有道路相连,任意两个不同的城市之间有且仅有一条直接或间接的道路。为了防止管理太过分散,每个省至少要有B个城市,为了能有效的管理,每个省最多只有3B个城市。每个省必须有一个省会,这个省会可以位于省内,也可以在该省外。但是该省的任意一个城市到达省会所经过的道路上的城市(除了最后一个城市,即该省省会)都必须属于该省。一个城市可以作为多个省的省会。聪明的你快帮帮这个国王吧!

    输入

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

    输出

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

    输入示例

    8 2
    1 2
    2 3
    1 8
    8 7
    8 6
    4 6
    6 5

    输出示例

    3
    2 1 1 3 3 3 3 2
    2 1 8

    数据规模及约定

    见“输入

    题解

    事实上这题没有无解情况。。。

    树上分块可以看看 http://www.cnblogs.com/shenben/p/6368457.html,如果不懂中文可以直接看代码。。。

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <cctype>
    #include <algorithm>
    using namespace std;
    
    const int BufferSize = 1 << 16;
    char buffer[BufferSize], *Head, *Tail;
    inline char Getchar() {
    	if(Head == Tail) {
    		int l = fread(buffer, 1, BufferSize, stdin);
    		Tail = (Head = buffer) + l;
    	}
    	return *Head++;
    }
    int read() {
    	int x = 0, f = 1; char c = Getchar();
    	while(!isdigit(c)){ if(c == '-') f = -1; c = Getchar(); }
    	while(isdigit(c)){ x = x * 10 + c - '0'; c = Getchar(); }
    	return x * f;
    }
    
    #define maxn 1010
    #define maxm 2010
    #define maxbl 1010
    
    int n, B, m, head[maxn], nxt[maxm], to[maxm];
    
    void AddEdge(int a, int b) {
    	to[++m] = b; nxt[m] = head[a]; head[a] = m;
    	swap(a, b);
    	to[++m] = b; nxt[m] = head[a]; head[a] = m;
    	return ;
    }
    
    int S[maxn], top, blid[maxn], cb, rt[maxbl];
    void build(int u, int fa) {
    	int bot = top;
    	for(int e = head[u]; e; e = nxt[e]) if(to[e] != fa) {
    		build(to[e], u);
    		if(top - bot >= B) {
    			rt[++cb] = u;
    			while(top > bot) blid[S[top--]] = cb;
    		}
    	}
    	S[++top] = u;
    	return ;
    }
    
    int main() {
    	n = read(); B = read();
    	for(int i = 1; i < n; i++) {
    		int a = read(), b = read();
    		AddEdge(a, b);
    	}
    	
    	build(1, 0);
    	while(top) blid[S[top--]] = cb;
    	
    	printf("%d
    ", cb);
    	for(int i = 1; i <= n; i++) printf("%d%c", blid[i], i < n ? ' ' : '
    ');
    	for(int i = 1; i <= cb; i++) printf("%d%c", rt[i], i < n ? ' ' : '
    ');
    	
    	return 0;
    }
    
  • 相关阅读:
    1061 Dating (20 分)
    1042 Shuffling Machine (20 分)简单模拟
    1132 Cut Integer (20 分)
    1100 Mars Numbers (20 分)
    1077 Kuchiguse (20 分)求字符串最长相同后缀
    1065 A+B and C (64bit) (20 分)大数 溢出
    1107 Social Clusters (30 分)并查集
    1079 Total Sales of Supply Chain (25 分)
    1078 Hashing (25 分)
    1063 Set Similarity (25 分)
  • 原文地址:https://www.cnblogs.com/xiao-ju-ruo-xjr/p/6791421.html
Copyright © 2020-2023  润新知