zoukankan      html  css  js  c++  java
  • SCOI2005 王室联邦

    传送门

    基础的树上分块题。如何保证一个块内的元素在[B,3B]之间呢?这里有一个很简单的方法是直接dfs。在每次进入一棵子树之前,我们记录一下现在栈顶编号,之后在返回的时候,如果当前编号减去所记录的编号的差值要大于等于B,那就直接把它们加到一个块内。最后可能会剩余一些元素,直接压到最后一个块内即可。

    这个方法是可以保证正确性的,即使你使得每棵子树的最大值是B-1,这样最后也只会压出一个大小为2B的块,然后最坏的情况就是再加上末尾剩余的元素,就形成了一个3B大小的块,不会有更坏的情况了。

    这道题本身不难,主要是为了树上分块来准备。

    看一下代码。

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<iostream>
    #include<cmath>
    #include<set>
    #include<vector>
    #include<map>
    #include<queue>
    #define rep(i,a,n) for(int i = a;i <= n;i++)
    #define per(i,n,a) for(int i = n;i >= a;i--)
    #define enter putchar('
    ')
    #define fr friend inline
    #define y1 poj
    #define mp make_pair
    #define pr pair<int,int>
    #define fi first
    #define sc second
    #define pb push_back
    #define I puts("Oops")
    
    using namespace std;
    typedef long long ll;
    const int M = 20005;
    const int N = 1000005;
    const int INF = 1000000009;
    const double eps = 1e-7;
    
    int read()
    {
        int ans = 0,op = 1;char ch = getchar();
        while(ch < '0' || ch > '9') {if(ch == '-') op = -1;ch = getchar();}
        while(ch >= '0' && ch <= '9') ans = ans * 10 + ch - '0',ch = getchar();
        return ans * op;
    }
    
    struct edge
    {
       int next,to,from;
    }e[M];
    
    int n,B,sta[M],top,ecnt,head[M],x,y,blo[M],cap[M],idx;
    
    void add(int x,int y)
    {
       e[++ecnt].to = y;
       e[ecnt].next = head[x];
       head[x] = ecnt;
    }
    
    void dfs(int x,int fa)
    {
       int cur = top;
       for(int i = head[x];i;i = e[i].next)
       {
          if(e[i].to == fa) continue;
          dfs(e[i].to,x);
          if(top - cur >= B)
          {
         cap[++idx] = x;
         while(top > cur) blo[sta[top--]] = idx;
          }
       }
       sta[++top] = x;
    }
    
    int main()
    {
       n = read(),B = read();
       rep(i,1,n-1) x = read(),y = read(),add(x,y),add(y,x);
       dfs(1,0);
       while(top) blo[sta[top--]] = idx;
       printf("%d
    ",idx);
       rep(i,1,n) printf("%d ",blo[i]);enter;
       rep(i,1,idx) printf("%d ",cap[i]);enter;
       return 0;
    }
    
    
  • 相关阅读:
    java处理数据库date类型数据
    in与exist , not in与not exist 的区别
    Eclipse的调试功能的10个小窍门
    关于Synchornized,Lock,AtomicBoolean和volatile的区别介绍
    推荐使用concurrent包中的Atomic类
    深入 Java 调试体系: 第 1 部分,JPDA 体系概览
    dom 绘制正方形
    dom 拖拽div
    dom 按着shift多选
    dom select选单
  • 原文地址:https://www.cnblogs.com/captain1/p/10105468.html
Copyright © 2011-2022 走看看