|
发表于 2022-10-30 13:03:27
|
显示全部楼层
本帖最后由 傻眼貓咪 于 2022-10-30 13:05 编辑
我试试写了代码练习练习:
- #include <iostream>
- #include <vector>
- #include <utility>
- using std::vector, std::pair;
- vector <pair <unsigned, unsigned>> trees;
- auto max = [](unsigned a, unsigned b) -> unsigned { return a > b ? a : b; };
- int Dijkstra(unsigned left, unsigned right, unsigned levels = 0) {
- return not(left) and not(right) ? levels : // 左右叶为 0,此为这支根的最深层,返回层数
- not(left) ? Dijkstra(trees[right].first, trees[right].second, levels + 1) : // 左叶为 0
- not(right) ? Dijkstra(trees[left].first, trees[left].second, levels + 1) : // 右叶为 0
- max(
- Dijkstra(trees[left].first, trees[left].second, levels + 1),
- Dijkstra(trees[right].first, trees[right].second, levels + 1)); // 比较左右叶节点深度,返回最深层层数
- }
- using std::cout, std::cin, std::endl;
- using std::make_pair;
- int main(void) {
- unsigned n, l, r;
- int ans = -(1 << 30);
- trees.push_back(make_pair(0, 0));
- cin >> n;
- while (n--) {
- cin >> l >> r;
- trees.push_back(make_pair(l, r));
- }
- ans = Dijkstra(1, 1);
- cout << ans << endl;
- return 0;
- }
复制代码 |
|