CSP-树上搜索 满分题解

题目回顾

树上搜索icon-default.png?t=N7T8https://sim.csp.thusaac.com/contest/32/problem/2

C++满分题解

思路概述

        接下来设计数据结构。存在对树的很多插入,剪枝操作,毋庸置疑用链表实现最为合适。 由于完成一次类别测试后,需要树结构的恢复,所以增加parent结点来快速完成剪枝后的拼接而不用从输入重塑树结构。

typedef   struct  treeNode
{
    int index;
    long long weight;
    treeNode* child;
    treeNode* lastChild;
    treeNode* brother;
    treeNode* prevBrother;
    treeNode* parent;
    int childID;

    treeNode(long long weight, int index) {
        this->weight = weight;
        this->index = index;
        this->parent = nullptr;
        this->child = nullptr;
        this->lastChild = nullptr;
        this->brother = nullptr;
        this->prevBrother = nullptr;
    }
} tree;
treeNode* myTree[2010];

        下面我们来实现程序框图里的抽象过程 。

根据输入构建树结构

        首先通过第一、二行输入,初始化所有的结点的 index 和 weight,通过第三行输入来实现结点之间的连接,构建出一棵树。我们定义一个函数来实现两结点之间的链接,顺序遍历第三行输入就能把一整棵树连接出来。

void linkNodes(treeNode* parent, treeNode* child) {
    child->parent = parent;
    if (!parent->child) {
        // 如果parent结点还没有孩子
        parent->child = child;
        parent->lastChild = child;
    }
    else
    {
        // 如果parent结点已经有了孩子
        parent->lastChild->brother = child;
        child->prevBrother = parent->lastChild;
        parent->lastChild = child;
    }
}

计算当前结点各子孙结点的

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值