標籤:des blog http io ar os sp for div
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#
思路如曹博所說,先dfs記錄離根的距離,來的方向的前驅。然後按距離排序,之後按此排序求有意義的增加距離。
直觀感受是,如果兩個葉子在一個分叉上,顯然深的節點更先被訪問,如果不在一個分叉上,那麼先算深的也沒什麼損失。最後,按照這個權值再對葉子排序一次,就是所要的結果。
#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