uojUNR3Bios
若是不輸出方案,是有一個經典的三分作法的spa
可是要輸出方案也是能夠貪心的
設\(d[i]\)爲\(i\)節點到最深的兒子的距離
貪心選擇\(d[i]\)大的便可code
#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; }