#include #include #include #include struct tree { std::vector child; int dist_root; int dist_leaf; int parent; }; int main() { int n; std::cin >> n; std::vector v(n); for (int i = 0; i < n - 1; i++) { int from, to; std::cin >> from >> to; v[from - 1].child.push_back(to - 1); } std::stack s, leafpoint; s.push(0); v[0].dist_root = 0; int dist = 1; while (!s.empty()) { int node = s.top(); s.pop(); for (int i = 0; i < v[node].child.size(); i++) { v[v[node].child[i]].dist_root = v[node].dist_root + 1; v[v[node].child[i]].parent = node; s.push(v[node].child[i]); } v[node].dist_leaf = 99999; if (v[node].child.size() == 0)leafpoint.push(node); } std::stack parent; while (!leafpoint.empty()) { int node = leafpoint.top(); leafpoint.pop(); v[node].dist_leaf = 0; parent.push(v[node].parent); int dist = 1; while (!parent.empty()) { int pa = parent.top(); parent.pop(); v[pa].dist_leaf = std::min(v[pa].dist_leaf, dist); if (pa == 0)break; parent.push(v[pa].parent); dist++; } } for (int i = 0; i < n; i++) { std::cout << std::min(v[i].dist_root, v[i].dist_leaf) << std::endl; } return 0; }