每⽇⼀题C++版(树的⾼度)
编程是很多偏计算机、⼈⼯智能领域必须掌握的⼀项技能,此编程能⼒在学习和⼯作中起着重要的作⽤。因此⼩⽩决定开辟⼀个新的板块“每⽇⼀题”,通过每天⼀道编程题⽬来强化和锻炼⾃⼰的编程能⼒(最起码不会忘记编程)
特别说明:编程题来⾃“⽜客⽹”和“领扣”以及热⼼⼩伙伴的题⽬。由于⼩⽩有时想锻炼某⼀类编程⽅法,所以提供的代码不⼀定是最优解,但是本⽂提供的编程代码均为通过测试代码。
题⽬描述
现在有⼀个由有序数对组成的树,树的节点都是⽤数字表⽰,现在给定这棵树上所有的⽗⼦关系,求这棵树的⾼度
古诗插图
输⼊描述:
赵王输⼊的第⼀⾏表⽰节点的个数n(1 ≤ n ≤ 1000,节点的编号为0到n-1)组成,
下⾯是n-1⾏,每⾏有两个整数,第⼀个数表⽰⽗节点的编号,第⼆个数表⽰⼦节点的编号
输出描述:
输出树的⾼度,为⼀个整数
子弦
输⼊
5
0 1摇钱树苗
0 2
1 3
1 4
输出
3
其实这⾥⾯的树,也就是链表。如果可以使⽤容器将同⼀⾼度的节点放在⼀个容器内,这个⾼度内的节点的⼦节点放在下⼀层绒球内。⽗节点放在上⼀层容器。由于我们不能总是先发现⽗节点,因此这个容器也会在⾸段插⼊数据。因此我们需要使⽤两端插⼊数据⽐较快的容器,因此我们选⽤list容器。
⽽这个容器内的元素也应该是⼀个容器(为了⽅便我们插⼊同样⾼度的新节点)。香港明星足球队
这样⾸先我们就在每⼀层中寻找⽗节点,如果找到,就将其⼦节点插⼊(存⼊)下⼀层;如果没有找到,我们就在每⼀层中寻找⼦节点,如果找到,就将其⽗节点插⼊(存⼊)上⼀层,并且将这个节点从需要插
⼊“树”中的数据⾥⾯删除。最后只要看这个list容器的size就可以了。
#include <iostream>#include <list>#include <vector>#include <algorithm>using namespace std;int main(){ int index; while (cin >> index) { list<vector<int>> joint; list<vector<int>> tree; for (int i = 0; i < index-1; i++) { vector<int> subjoint; int father, son; cin >> father >> son; subjoint.push_back(father); subjoint.push_back(son); joint.push_back(subjoint); if (pty()) { vector<int> father_t; father_t.push_back(father); vector<int> son_t; son_t.push_back(son); tree.push_back(father_t); tree.push_back(son_t); } } while (!pty()) { for (auto i = joint.cbegin(); i != d(); ) { bool add = fal; for (auto m = tree.begin(); m != d(); m++) { int father = (*i)[0]; int son = (*i)[1]; auto findfather = find((*m).cbegin(), (*m).cend(), father); auto findson = find((*m).cbegin(), (*m).cend(), son); auto lastone = d(); lastone--; if (findfather != (*m).cend())
因为想念 { if (m == lastone) { vector<int> subjoint; subjoint.push_back(son); tree.push_back(subjoint); i = a(i); add = true; break; } if (m != lastone) { m++;
手套(*m).push_back(son); m--; i = a(i); add = true; break; } } el if (findson != (*m).cend()) { if (m == tree.begin()) {
vector<int> subjoint; subjoint.push_back(father); tree.push_front(subjoint);
i = a(i); add = true; break; } if (m == tree.begin()) { m++; (*m).push_back(father); m--; i = a(i); add = true; break; } } } if (!add) { i++; } } } cout <<
蒲瓜瓜tree.size() << endl; } return 0;}