#include #define MAX 100000 int calc(int, int); int lr[3][MAX], count[MAX], memo[MAX], ne[MAX], ha[MAX]; int main(void) { int n, i; scanf("%d", &n); for(i = 0; i < n - 1; i++) { int x, y; scanf("%d%d", &x, &y); x--; y--; lr[ count[x] ][x] = y; count[x]++; lr[ count[y] ][y] = x; count[y]++; } calc(0, 0); for(i = 0; i < n; i++) { printf("%d\n", ne[i] < ha[i] ? ne[i] : ha[i]); } return 0; } int calc(int i, int c) { ne[i] = c; memo[i] = 1; int m = MAX, temp; if(memo[ lr[0][i] ] == 0) { temp = calc(lr[0][i], c + 1) + 1; m = (temp < m ? temp : m); } if(memo[ lr[1][i] ] == 0) { temp = calc(lr[1][i], c + 1) + 1; m = (temp < m ? temp : m); } if(memo[ lr[2][i] ] == 0) { temp = calc(lr[2][i], c + 1) + 1; m = (temp < m ? temp : m); } m = (m == MAX ? 0 : m); ha[i] = m; return m; }