问题描述
通过dp树获取树中最大距离,以及高度;使用结构体将树的信息一级一级往回传递;
解析
代码
/*----------------------------------------------------------------------
> File Name: getMaxdisDP.cpp
> Author: Jxiepc
> Mail: Jxiepc
> Created Time: Mon 14 Mar 2022 08:20:00 AM CST
----------------------------------------------------------------------*/
/**
* 通过dp树获取树中最大距离,以及高度
* */
#include <iostream>
/** 树结构 */
struct node {
int val;
struct node* left;
struct node* right;
};
typedef struct node Node;
/** 树返回的信息*/
class Info {
public:
int maxDis;
int height;
Info(int ids, int h)
: maxDis(ids), height(h){
}
};
Info solve(Node *x) {
if(x == nullptr) {
return Info(0, 0);
}
Info lInfo = solve(x->left);
Info rInfo = solve(x->right);
int p1 = lInfo.maxDis;
int p2 = rInfo.maxDis;
int p3 = lInfo.height + rInfo.height + 1;
/* 左右最大距离与树的高度 */
int maxDis = p1 > p2 ? p1 : p2;
maxDis = p3 > maxDis ? p3 : maxDis;
/* 高度 */
int h = lInfo.height > rInfo.height ? lInfo.height + 1 : rInfo.height + 1;
return Info(maxDis, h);
}
int main(int argc, char* argv[])
{
Node n1= {1, nullptr, nullptr};
Node n2= {2, nullptr, nullptr};
Node n3= {3, nullptr, nullptr};
Node n4= {4, nullptr, nullptr};
Node n5= {5, nullptr, nullptr};
Node n6= {6, nullptr, nullptr};
Node n7= {7, nullptr, nullptr};
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
n3.left = &n6;
n3.right = &n7;
Info ret = solve(&n1);
std::cout << "最大距离:" << ret.maxDis << " 最大高度:" << ret.height << std::endl;
return 0;
}
拓展实例应用
公司宴会将邀请员工求参加,要求如员工去参加,则其下属就不能去,若该员工不去,则其下属可以去,求公司本次宴会的员工快乐值最大;
/*----------------------------------------------------------------------
> File Name: getMaxDisHappyDp.cpp
> Author: Jxiepc
> Mail: Jxiepc
> Created Time: Mon 14 Mar 2022 09:17:45 AM CST
----------------------------------------------------------------------*/
/**
* 获取员工最大快乐值,每个员工来,则其直接下属不能来
* */
#include <iostream>
#include <vector>
struct employee {
int happy;
std::vector<struct employee *> nexts;
};
typedef struct employee el;
class Info {
public:
int lMHappy;
int nMHappy;
Info(int l, int n)
: lMHappy(l), nMHappy(n){
}
};
Info solve(el *e) {
if(e->nexts.empty()) {
return Info(e->happy, 0);
}
int l = e->happy;
int n = 0;
for(auto& i : e->nexts) {
Info nInfo = solve(i);
l += nInfo.nMHappy;
n += nInfo.nMHappy > nInfo.lMHappy ? nInfo.nMHappy : nInfo.lMHappy;
}
return Info(l, n);
}
int main(int argc, char* argv[])
{
el head, n1, n2, n3, n4, n5;
head.happy = 10;
n1.happy = 10;
n2.happy = 20;
n3.happy = 10;
n4.happy = 40;
n4.happy = 30;
head.nexts.push_back(&n1);
head.nexts.push_back(&n3);
n1.nexts.push_back(&n2);
n3.nexts.push_back(&n4);
n3.nexts.push_back(&n5);
Info ret = solve(&head);
ret = ret.lMHappy > ret.nMHappy ? ret.lMHappy : ret.nMHappy;
std::cout << "最大快乐值为:" << ret << std::endl;
return 0;
}