码迷,mamicode.com
首页 > 其他好文 > 详细

SCOI2005 王室联邦

时间:2018-12-12 00:39:30      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:www.   tchar   char   http   i++   code   std   amp   如何   

传送门

基础的树上分块题。如何保证一个块内的元素在[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(‘\n‘)
#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\n",idx);
   rep(i,1,n) printf("%d ",blo[i]);enter;
   rep(i,1,idx) printf("%d ",cap[i]);enter;
   return 0;
}

SCOI2005 王室联邦

标签:www.   tchar   char   http   i++   code   std   amp   如何   

原文地址:https://www.cnblogs.com/captain1/p/10105468.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!