bzoj1086: [SCOI2005]王室联邦(贪心)

35 篇文章 0 订阅

题目传送门

解法:
子树大于等于B就直接那啥嘛。
其实不用管3B的因为你遇到B就分了。
然后剩下的也肯定不大于B,那么加起来也肯定不超过3B。
用一个栈记录下访问过的点就好了。
一开始写错了还挂了一次。
因为栈里有可能有别的省的点啊。

代码实现:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
struct node {int x,y,next;}a[2100];int len,last[1100];
void ins(int x,int y) {len++;a[len].x=x;a[len].y=y;a[len].next=last[x];last[x]=len;}
int tot[1100],sta[1100],top,belong[1100],B,cnt,ans[1100];
void dfs(int x,int fa) {
    sta[++top]=x;
    for(int k=last[x];k;k=a[k].next) {
        int y=a[k].y;
        if(y!=fa) {
            dfs(y,x);tot[x]+=tot[y];
            if(tot[x]>=B) {
                tot[x]=0;cnt++;ans[cnt]=x;
                while(sta[top]!=x)belong[sta[top--]]=cnt;
            }
        }
    }tot[x]++;
}
void find(int x,int fa,int s) {
    if(belong[x]!=0)s=belong[x];
    else belong[x]=s;
    for(int k=last[x];k;k=a[k].next) {
        int y=a[k].y;
        if(y!=fa) find(y,x,s);
    }
}
int main() {
    int n;scanf("%d%d",&n,&B);
    len=0;memset(last,0,sizeof(last));
    for(int i=1;i<n;i++) {int x,y;scanf("%d%d",&x,&y);ins(x,y);ins(y,x);}
    if(n<B) {printf("0\n");return 0;}
    cnt=top=0;memset(sta,0,sizeof(sta));memset(belong,0,sizeof(belong));dfs(1,0);
    if(cnt==0) {cnt++;ans[1]=1;}
    find(1,0,cnt);printf("%d\n",cnt);
    for(int i=1;i<n;i++)printf("%d ",belong[i]);printf("%d\n",belong[n]);
    for(int i=1;i<cnt;i++)printf("%d ",ans[i]);printf("%d\n",ans[cnt]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值