• 【BZOJ1086】王室联邦(SCOI2005)-树分块


    测试地址:王室联邦
    做法:本题需要用到树分块。
    这题是树分块的模板,我们来看一下该怎么分。
    DFS整棵树,维护一个栈,当遍历完一个点时将这个点加入栈中。对于一个点,每遍历完它的一棵子树,检查栈内元素是否达到B个,如果达到就把这些元素分成一个块(本题中是一个省),块的根设为当前点(本题中为省会)。
    但是,如果在一棵子树中还有剩余的点,而这些剩余的点数和另一棵子树中底部的点加起来达到B个,按照算法会被分成一块,但是这样显然不满足题目条件。所以我们对于每个点另外维护一个临时栈底,保证不会访问在这个点之前已经访问过的点。
    这样一来,遍历完每个点后都只会给它的父亲留下小于B个点,而这些点最多会和另外B个点合成一块,那么块的大小就在[B,2B]这个区间内。那么为什么题目给到3B呢?在遍历完整棵树的根后,还剩下小于B个点,我们把这些点跟上一次合成的块进行合成,那么点数最多也不超过3B。因此我们就找到了一个满足题目要求的划分。
    以下是本人代码:

    #include <bits/stdc++.h>
    using namespace std;
    int n,blocksiz,first[1010]={0},tot=0,st[1010],top=0;
    int block[1010],rt[1010],cnt=0;
    struct edge
    {
        int v,next;
    }e[2010];
    
    void insert(int a,int b)
    {
        e[++tot].v=b,e[tot].next=first[a],first[a]=tot;
    }
    
    void dfs(int v,int fa)
    {
        int bottom=top;
        for(int i=first[v];i;i=e[i].next)
            if (e[i].v!=fa)
            {
                dfs(e[i].v,v);
                if (top-bottom>=blocksiz)
                {
                    rt[++cnt]=v;
                    while (top!=bottom) block[st[top--]]=cnt;
                }
            }
        st[++top]=v;
    }
    
    int main()
    {
        scanf("%d%d",&n,&blocksiz);
        for(int i=1;i<n;i++)
        {
            int a,b;
            scanf("%d%d",&a,&b);
            insert(a,b),insert(b,a);
        }
    
        dfs(1,0);
        while (top) block[st[top--]]=cnt;
    
        printf("%d
    ",cnt);
        if (cnt)
        {
            for(int i=1;i<=n;i++)
                printf("%d ",block[i]);
            printf("
    ");
            for(int i=1;i<=cnt;i++)
                printf("%d ",rt[i]); 
        }
    
        return 0; 
    }
  • 相关阅读:
    洛谷 P1886 滑动窗口(单调队列)
    POJ 2559 Largest Rectangle in a Histogram(单调栈)
    eclipse开发velocity实例(初学)
    Spring MVC 教程,快速入门,深入分析
    传智博客(JavaWeb方面的所有知识)听课记录(经典)
    JSP/SERVLET入门教程--Servlet 使用入门
    javaweb入门实例---servlet例子
    Eclipse快捷键大全(转载)
    简单java web应用程序搭建与部署
    Servlet 工作原理解析
  • 原文地址:https://www.cnblogs.com/Maxwei-wzj/p/9793528.html
Copyright © 2020-2023  润新知