Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int n;
- vector <vector <int> > graph;
- vector <deque <int> > result;
- vector <int> position_of_answer;
- vector <pair <int, int> > all;
- void dfs(int v) {
- for (auto to : graph[v])
- dfs(to);
- /**int pos = v;
- for (auto to : graph[v]) {
- if ((int)result[position_of_answer[to]].size() > (int)result[position_of_answer[pos]].size())
- pos = position_of_answer[to];
- }
- position_of_answer[v] = pos;**/
- result[v].push_back(v);
- for (auto to : graph[v]) {
- //if (to == graph[v].back())
- //reverse(result[to].begin(), result[to].end());
- all.push_back({result[to][0], result[to].back()});
- for (auto el : result[to])
- result[v].push_back(el);
- result[to].clear();
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- cin >> n;
- graph.resize(n);
- result.resize(n);
- position_of_answer.resize(n);
- for (int i = 0; i < n - 1; i++) {
- int x;
- cin >> x;
- graph[x - 1].push_back(i + 1);
- }
- dfs(0);
- map <int, int> smth;
- for (int i = 0; i < n; i++)
- smth[result[0][i]] = i;
- vector <int> used(n, -1);
- for (auto el : all) {
- int l = el.first, r = el.second;
- //cout << l << " " << r << "aaa\n";
- if (used[r] == -1 || used[r] > smth[l])
- used[r] = smth[l];
- }
- vector <int> ans(n);
- for (int i = 0; i < n; i++) {
- if (used[i] == -1)
- continue;
- int l = used[i], r = smth[i];
- int step = 0;
- //cout << l << " " << r << endl;
- for (int j = l + 1; j <= r; j += 2) {
- ans[l + step] = result[0][j];
- step++;
- }
- for (int j = r - (r - l) % 2; j >= l; j -= 2) {
- ans[l + step] = result[0][j];
- step++;
- }
- }
- for (auto el : ans)
- cout << el + 1 << " ";
- cout << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement