uoj【UNR #3】To Do Tree 【贪心】
题目链接
题解
如果不输出方案,是有一个经典的三分做法的
但是要输出方案也是可以贪心的
设\(d[i]\)为\(i\)节点到最深的儿子的距离
贪心选择\(d[i]\)大的即可
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define cls(s,v) memset(s,v,sizeof(s))
#define mp(a,b) make_pair<int,int>(a,b)
#define cp pair<int,int>
using namespace std;
const int maxn = 100005,maxm = 100005,INF = 0x3f3f3f3f;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = 0; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 1) + (out << 3) + c - 48; c = getchar();}
return flag ? out : -out;
}
priority_queue<cp> q;
vector<int> out[maxn];
int ls[maxn],rb[maxn],d[maxn];
int n,m,ans;
void dfs(int u){for (int k = ls[u]; k; k = rb[k]) dfs(k),d[u] = max(d[u],d[k] + 1);}
void work(){
q.push(mp(d[1],1));
int cnt = 0;
while (cnt < n){
ans++;
for (int i = 1; i <= m; i++){
if (q.empty()) break;
out[ans].push_back(q.top().second); q.pop();
cnt++;
}
for (unsigned int j = 0; j < out[ans].size(); j++){
int u = out[ans][j];
for (int k = ls[u]; k; k = rb[k])
q.push(mp(d[k],k));
}
}
printf("%d\n",ans);
for (int i = 1; i <= ans; i++,puts("")){
printf("%d ",out[i].size());
for (unsigned int j = 0; j < out[i].size(); j++)
printf("%d ",out[i][j]);
}
}
int main(){
n = read(); m = read(); int f;
for (int i = 2; i <= n; i++){
f = read(); rb[i] = ls[f]; ls[f] = i;
}
dfs(1);
work();
return 0;
}