题目链接:http://codevs.cn/problem/1501/
解题思路:
直接模拟
注意点:
1.需要注意只有根节点, 即一个点的情况
AC代码::
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 1e3;
int n;
int h[maxn], e[maxn], ne[maxn], idx;
int height, width;
int d[maxn];
inline void read(int& x) {
char w = getchar(); x = 0;
while(w < '0' || w > '9') w = getchar();
while(w >= '0' && w <= '9') x = x * 10 + w - '0', w = getchar();
}
inline void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
inline void bfs(int u) {
queue<int> q;
while(q.size()) q.pop();
q.push(u), d[u] = 1;
int tmpw = 1, tmph = 1;
width = height = 1;
while(q.size()) {
int t = q.front(); q.pop();
for(int i = h[t]; i + 1; i = ne[i]) {
int v = e[i];
d[v] = d[t] + 1;
q.push(v);
height = max(height, d[v]);
if(tmph == d[v]) tmpw ++;
else tmph = d[v], tmpw = 1;
width = max(width, tmpw);
}
}
}
int main(void) {
read(n);
memset(h, -1, sizeof h);
for(int i = 1; i <= n; i ++) {
int lc, rc; read(lc), read(rc);
if(lc) add(i, lc);
if(rc) add(i, rc);
}
bfs(1);
// for(int i = 1; i <= n; i ++) printf("%d %d\n", i, d[i]);
printf("%d %d\n", width, height);
return 0;
}
总结:写代码时需要写一行就检查一下,这样可以避免一些细小而难找的BUG。
树的宽度:节点最大的那层的节点数。