forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhyacinth.cpp
75 lines (62 loc) · 1.61 KB
/
hyacinth.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <bits/stdc++.h>
using namespace std;
int currfreq = 1;
void dfs(vector<vector<int>>& adj, vector<pair<int,int>>& freq, int curr, int prev, int root) {
int children = 0;
for(auto next : adj[curr]) {
if(next != prev) {
children++;
}
}
// If root node, assign two new vals
if(curr == root) {
freq[curr].first = currfreq++;
freq[curr].second = currfreq++;
}
else {
// If a leaf, copy the parents
if(children == 0) {
freq[curr].first = freq[prev].first;
freq[curr].second = freq[prev].second;
}
// If not a leaf, copy parent's second into our first, assign a new second
else {
freq[curr].first = freq[prev].second;
freq[curr].second = currfreq++;
}
}
for(auto next : adj[curr]) {
if(next != prev) {
dfs(adj, freq, next, curr, root);
}
}
}
int main() {
int n;
cin >> n;
vector<pair<int,int>> freq(n, {-1,-1});
vector<vector<int>> adj(n);
vector<pair<int,int>> input;
vector<int> deg(n, 0);
for(int i = 0; i < n-1; i++) {
int n1, n2;
cin >> n1 >> n2;
n1--; n2--;
adj[n1].push_back(n2);
adj[n2].push_back(n1);
deg[n1]++;
deg[n2]++;
input.push_back({n1,n2});
}
int root;
for(int i = 0; i < n; i++) {
if(deg[i] == 1) {
root = i;
break;
}
}
dfs(adj, freq, root, -1, root);
for(int i = 0; i < n; i++) {
cout << freq[i].first << " " << freq[i].second << endl;
}
}