题目传送门
题目大意:
题面说得很清楚了。
思考过程:
其实这个题很奇怪,既没要求最多可能分多少个省,又没要求城市数最多的省的城市数最小是多少,所以有很多种做法。
具体做法:
从1开始做dfs,对所有点维护一个栈,第一次到这个点则让他入栈,回溯时如果比第一次到时栈中元素多了n个或以上,则将这一部分弹栈,划分成一个省,省会为当前回溯的城市,最后未划分的城市和最后被划分一个省合为一个省就行了,这样就能保证划分的正确性。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn=1100;
struct stu
{
int to,next;
}road[maxn*2]; int first[maxn],cnt=0;
int be[maxn],root[maxn],fa[maxn],stack1[2*maxn];
int n,b,top;
void addedge(int x,int y)
{
road[++cnt].to=y;
road[cnt].next=first[x];
first[x]=cnt;
}
void dfs(int now)
{
int nowtop=top;
for(int i=first[now];i;i=road[i].next)
{
int to=road[i].to;
if(to==fa[now]) continue;
fa[to]=now;
dfs(to);
if(top-nowtop>=b)
{
cnt++;
root[cnt]=now;
while(nowtop!=top)
{
be[stack1[top]]=cnt;
top--;
}
}
}
stack1[++top]=now;
}
int main()
{
scanf("%d%d",&n,&b);
for(int i=1;i<=n-1;i++)
{
int x,y;
scanf("%d%d",&x,&y);
addedge(x,y);addedge(y,x);
}
cnt=0;
dfs(1);
while(top>=1)
{
be[stack1[top]]=cnt;
top--;
}
printf("%d\n",cnt);
for(int i=1;i<=n;i++) printf("%d ",be[i]); printf("\n");
for(int i=1;i<=cnt;i++) printf("%d ",root[i]); printf("\n");
return 0;
}