Description
计算输入有序树的深度和有序树转化为二叉树之后树的深度。
Input
输入包含多组数据。每组数据第一行为一个整数n(2<=n<=30000)代表节点的数量,接下来n-1行,两个整数a、b代表a是b的父亲结点。
Output
输出当前树的深度和转化成二叉树之后的深度。
Sample Input
5
1 5
1 3
5 2
1 4
Sample Output
3 4
HINT
Append Code
析:这个题很好说,只要遍历一次就能得到答案,由于要先有序树转成二叉树,我也没听过,我百度了一下怎么转,看到百度百科中有,我总结一下就是,左儿子,
右兄弟,和那个字典树有的一拼,也就是左结点是儿子结点,而右结点是兄弟结点,那么我们可以用两个参数来记录深度,二叉树既然是右兄弟,那么同一深度的就会多一层,
加1,这样最大的就是答案。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #define debug puts("+++++") //#include <tr1/unordered_map> #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; //using namespace std :: tr1; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const LL LNF = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 3e4 + 5; const LL mod = 1e3 + 7; const int N = 1e6 + 5; const int dr[] = {-1, 0, 1, 0, 1, 1, -1, -1}; const int dc[] = {0, 1, 0, -1, 1, -1, 1, -1}; const char *Hex[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; inline LL gcd(LL a, LL b){ return b == 0 ? a : gcd(b, a%b); } inline int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } inline int lcm(int a, int b){ return a * b / gcd(a, b); } int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline int Min(int a, int b){ return a < b ? a : b; } inline int Max(int a, int b){ return a > b ? a : b; } inline LL Min(LL a, LL b){ return a < b ? a : b; } inline LL Max(LL a, LL b){ return a > b ? a : b; } inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } vector<int> G[maxn]; bool in[maxn]; int ans1, ans2; void dfs(int u, int cnt1, int cnt2){ ans1 = Max(ans1, cnt1); ans2 = Max(ans2, cnt2); for(int i = 0; i < G[u].size(); ++i) dfs(G[u][i], cnt1+1, cnt2+i+1); } int main(){ while(scanf("%d", &n) == 1){ for(int i = 0; i <= n; ++i) G[i].clear(), in[i] = 0; int u, v; for(int i = 1; i < n; ++i){ scanf("%d %d", &u, &v); G[u].push_back(v); in[v] = true; } ans1 = ans2 = 0; for(int i = 1; i <= n; ++i) if(!in[i]){ dfs(i, 1, 1); break; } printf("%d %d ", ans1, ans2); } return 0; }