AcWing4313. 满二叉树等长路径

题目链接

https://www.acwing.com/problem/content/4316/

题目思路

贪心

从最底层向高层遍历,同一分支的两个结点比较,将大值赋给父节点, ans += 最大值 + 最小值

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;
const int N = 1000010;
int length[N];
int dist[N];
int n;

int main()
{
    cin >> n;
    int cnt = 2;
    
    for(int i = 2; i < pow(2, n + 1); i ++ )
    {
        cin >> length[i];
        dist[i] = length[i] + dist[i / 2];
    }
    
    int ans = 0;
    
    for(int i = pow(2, n + 1) - 1; i > 1; )
    {
        dist[i / 2] = max(dist[i], dist[i - 1]);
        ans += max(dist[i], dist[i - 1]) - min(dist[i], dist[i - 1]);
        i -= 2;
    }
    
    cout << ans << endl;
    
    return 0;
}
贪心 + 递归

y总代码

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 2050;

int n;
int w[N];
int ans;

int dfs(int u)
{
    if (u * 2 > (1 << n + 1) - 1) return 0;

    int l = dfs(u * 2) + w[u * 2];
    int r = dfs(u * 2 + 1) + w[u * 2 + 1];
    ans += abs(l - r);
    return max(l, r);
}

int main()
{
    cin >> n;
    for (int i = 2; i <= (1 << n + 1) - 1; i ++ ) cin >> w[i];
    dfs(1);

    cout << ans << endl;
    return 0;
}

作者:yxc
链接:https://www.acwing.com/activity/content/code/content/2831011/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @   vacilie  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示
主题色彩