for (int i = 2; i <= n; i++) { scanf("%d", p + i); G[p[i]].push_back(i); } Match(1, 1); queue<int> que0; priority_queue<P> que1;//que0: matched que1: unmatched for (auto i: G[0]) { Match(i, i); } countUnmatchedNodesForAllTrees(); for (auto i: G[0]) { if (matched[i]) { que0.push(i); } else que1.push(P(unmatched_nodes[i].size(),i)); }
addUnmatchedNodesToRoot(1); while (!que0.empty()) { int u = que0.front(); que0.pop(); p[u] = 1; addUnmatchedNodesToRoot(u); }
while (!que1.empty()) { int u = que1.top().second; que1.pop(); if (!S.empty()){ int v = *S.begin(); p[u] = v; cnt++; addUnmatchedNodesToRoot(u); S.erase(u); S.erase(v); } else { p[u] = 1; addUnmatchedNodesToRoot(u); } } printf("%d\n", cnt); for (int i = 2; i <= n; i++) printf("%d%c", p[i], (i == n?10:32)); }