复习一哈
【北大公开课】 算法设计与分析 屈婉玲教授https://www.bilibili.com/video/BV1Ls411W7PB?p=35 p35~p42
补充
源码用到了 容器 与 迭代器
c++——标准库类型vector(容器)_阿根不会dWings的博客-CSDN博客https://blog.csdn.net/qq_22046265/article/details/123877704?spm=1001.2014.3001.5502c++——迭代器_初识(iterator)_阿根不会dWings的博客-CSDN博客https://blog.csdn.net/qq_22046265/article/details/124106687?spm=1001.2014.3001.5502
1.问题
有如下所示的数塔,要求从顶层走到底层,若每一步只能走到相邻的结点,则经过的结点的数字之和最大是多少?
示例:
2.源码
#include
#include
using namespace std;
typedef struct elem
{
int data;
int val;
elem* next;
elem* lFather;
elem* rFather;
elem* lChild;
elem* rChild;
}Node,*pNdoe;
constexpr int Tree_arr[] = { 9,12,15,10,6,8,2,18,9,5,19,7,10,4,16 };
constexpr int Tree_depth = 5;
vector v;//储存指针
void CreatTree()
{
pNdoe p = new Node;
int index = 0;
p->data = p->val = Tree_arr[index++];//第0层 手动添加
p->lChild = p->lFather = p->rChild = p->rFather = p->next = nullptr;
v.push_back(p);
pNdoe temp = nullptr;
for (int i = 1; i < Tree_depth; i++)//赋值
{
for (int j = 0; j <= i; j++)
{
temp = new Node;
temp->data = temp->val = Tree_arr[index++];
temp->lChild = temp->rChild = temp->lFather = temp->rFather = temp->next = nullptr;
if (j == 0)
{
temp->rFather = *(v.end() - i);
temp->rFather->lChild = temp;
}
if (j == i)
{
temp->lFather = *(v.end() - j - 1);
temp->lFather->rChild = temp;
}
if (j != 0 && j != i)
{
temp->lFather = *(v.end() - i - 1);
temp->rFather = *(v.end() - i);
temp->lFather->rChild = temp;
temp->rFather->lChild = temp;
}
v.push_back(temp);
}
}
return ;
}
pNdoe Dynamic()//动态规划
{
for (int i=v.size()-1;i>=0;i--)
{
if (v[i] != nullptr)//判断是否遍历完成
{
if (v[i]->rChild != nullptr && v[i]->rChild != nullptr)
{
if (v[i]->lChild->val >= v[i]->rChild->val)
{
v[i]->val += v[i]->lChild->val;
v[i]->next = v[i]->lChild;
}
else
{
v[i]->val += v[i]->rChild->val;
v[i]->next = v[i]->rChild;
}
}
}
else
{
cout << "容器所指为空" << endl;
}
}
return v[0];//返回首指针
}
void Print(pNdoe p)
{
cout <val << endl;
cout << "最大路径是:";
while (p!=nullptr)
{
cout << p->data << "->";
p = p->next;
}
cout << "aGen" << endl << "aGen 是世界的镜头 0.0" << endl;
}
void main()
{
CreatTree();
Print(Dynamic());
return;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)