https://codility.com/programmers/challenges/fluorum2014
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1273
http://blog.csdn.net/caopengcs/article/details/36872627
http://www.quora.com/ how-do-i-determine-the-order-of-visiting-all-leaves-of-a-rooted-tree-so-that-in-each-step-i-visit-a-leaf-whose-path-from- root-contains-the-most-unvisited-nodes#
Thinking as Cao Bo said, first DFS records the distance from the root, the direction of the precursor. Then sort by distance, then sort by this to make a meaningful increase in distance.
The intuitive feeling is that if the two leaves on a fork, it is clear that the deep node is first accessed, if not a fork, then the first depth is no loss. Finally, sort the leaves again according to this weight, which is the desired result.
#include <iostream>using namespace Std;void dfs (vector<vector<int>> &tree, vector<int> &parent, vector<int> &depth, vector<bool> &visited, int root, int dep) {Visited[root] = true; Depth[root] = DEP; for (int i = 0; i < tree[root].size (); i++) {if (Visited[tree[root][i]]) continue; Parent[tree[root][i]] = root; DFS (tree, parent, depth, visited, Tree[root][i], dep + 1); }}vector<int> solution (int K, vector<int> &t) {int n = t.size (); Vector<vector<int>> tree (n); for (int i = 0; i < n; i++) {if (t[i]! = i) {tree[i].push_back (t[i]); Tree[t[i]].push_back (i); }} vector<int> parent (n); Vector<int> depth (n); Vector<bool> visited (n); DFS (tree, parent, depth, visited, K, 0); Vector<vector<int>> CNT (n); for (int i = 0; i < n; i++) {Cnt[depth[i]].push_back (i); } vector<int> ordered; for (int i = n-1; I >= 0, i--) {for (int j = 0; J < Cnt[i].size (); j + +) {Ordered.push_back (CNT I [j]); }} vector<int> Res; Vector<int> length (n); Visited.clear (); Visited.resize (n); Visited[k] = true; for (int i = 0; i < ordered.size (); i++) {int len = 0; int x = Ordered[i]; while (!visited[x]) {visited[x] = true; x = Parent[x]; len++; } Length[ordered[i]] = len; cout << "length[" << Ordered[i] << "]:" << len << Endl; } cnt.clear (); Cnt.resize (n); for (int i = 0; i < length.size (); i++) {cnt[length[i]].push_back (i); } res.push_back (K); for (int i = Cnt.size ()-1, i > 0; i--) {for (int j = 0, J < Cnt[i].size (); j + +) {Res.push_back (Cnt[i][j]); }} return res;}
*[codility]country Network