MC0244多重堡垒
码蹄集OJ-多重堡垒
一、问题概述
(一)问题背景
小码哥沉迷游戏 “多重堡垒”,该游戏可抽象为满二叉树结构(满二叉树是指除最后一层外,每层节点数达最大值,且最后一层节点集中在左侧 ),需计算其复杂程度,以此考查对满二叉树特性、节点复杂程度计算规则及算法实现的理解。
(二)问题目标
给定满二叉树的节点个数 n
和按层序遍历(每层从左到右遍历,一层结束遍历下一层 )的节点权值序列 v
,计算该游戏的复杂程度,即所有节点复杂程度之和。每个节点的复杂程度为:以该节点为根的子树中,所有节点(含根节点 )的权值乘以到根节点的边数(节点到自身边数为 0 )的结果中的最大值。
五、示例验证
(一)样例输入输出
样例输入:
3
6 2 7
样例输出:
7
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 7;
int n, a[N], ans;int getMax(int index, int edge) {if (index > n)return 0;int rootValue = edge * a[index]; int leftValue = getMax(index * 2, edge + 1);int rightValue = getMax(index * 2 + 1, edge + 1);return max(max(rightValue, leftValue), rootValue);
}int main() {cin >> n;for (int i = 1; i <= n; i++)cin >> a[i];for (int i = 1; i <= n; i++)ans += max(getMax(i * 2, 1), getMax(i * 2 + 1, 1));cout << ans;return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 7;
int n, a[N], ans;int getMax(int index, int edge)
{if (index > n)return 0;int rootValue = edge * a[index]; int leftValue = getMax(index * 2, edge + 1);int rightValue = getMax(index * 2 + 1, edge + 1);return max(max(rightValue, leftValue), rootValue);
}int main() {cin >> n;for (int i = 1; i <= n; i++)cin >> a[i];for (int i = 1; i <= n; i++)//计算简化处理 ans += max(getMax(i * 2, 1), getMax(i * 2 + 1, 1));cout << ans;return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 7;
int n, a[N], ans;
int getMax(int index,int edge)
{if (index > n)return 0;int rootValue = edge * a[index]; int leftValue = getMax(index * 2, edge + 1);int rightValue = getMax(index * 2 + 1, edge + 1);return max(max(rightValue, leftValue), rootValue);
}int main() {cin >> n;for (int i = 1; i <= n; i++)cin >> a[i];for (int i = 1; i <= n; i++)ans += getMax(i,0);cout << ans;return 0;
}