您的位置:首页 > 其它

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

2018-03-03 10:10 281 查看
题目传送门



解法:

子树大于等于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
);
for(int i=1;i<cnt;i++)printf("%d ",ans[i]);printf("%d\n",ans[cnt]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: