《数据结构、算法与应用C++语言描述》- 最小输者树模板的C++实现

输者树

完整可编译运行代码见:Github::Data-Structures-Algorithms-and-Applications/_31loserTree

输者树:每一个内部节点所记录的都是比赛的输者,晋级的节点记录在边上。本文中,赢者是分数较低的那个,输者是分数高的那个。教材的举例是这样的。

在这里插入图片描述

更好理解的解释是,参考地址。

  • a与b比赛,输者是b,赢者是a,将b放到内部节点,将a放到边上
  • c与d比赛,输者是d,赢者是c,将d放到内部节点,将c放到边上
  • e与f比赛,输者是e,赢者是f,将e放到内部节点,将f放到边上
  • g与h比赛,输者是h,赢者是g,将h放到内部节点,将g放到边上
  • a与c比赛,输者是c,赢者是a,将c放到内部节点,将a放到边上
  • f与g比赛,输者是g,赢者是f,将g放到内部节点,将f放到边上
  • a与f比赛,输者是a,赢者是f,将a放到内部节点,将f放到边上
  • 将最终赢者放到数组的第0个元素

在loserTree的模板实现中,可以使用一个数组来存储输者、另一个数组存储赢者。

在这里插入图片描述

输者树比赢者树的优势

当改变的元素是上一场比赛的最终赢家的话,内部节点存储了所有该赢家的输者。在重新组织比赛时,只需要与父亲节点进行比较,而不需要获取到父亲节点的另外一个节点,然后与其比较,可以减少访存的时间。

输者树的实现

main.cpp

/*
Project name :			_30winnerTree
Last modified Date:		2023年12月19日16点48分
Last Version:			V1.0
Descriptions:			最小输者树——main函数
*/
#include "MinimumLoserTree.h"
int main(){
    MinimumLoserTreeTest();
    return 0;
}

MinimumLoserTree.h

/*
Project name :			_30winnerTree
Last modified Date:		2023年12月19日16点48分
Last Version:			V1.0
Descriptions:			最小输者树——模板类
*/

#ifndef _31LOSERTREE_MINIMUMLOSERTREE_H
#define _31LOSERTREE_MINIMUMLOSERTREE_H
#include<iostream>
#include "loserTree.h"
#include "myExceptions.h"
using namespace std;

void MinimumLoserTreeTest();

template<class T>
class MinimumLoserTree : public loserTree<T> {
public:
    /*构造函数*/
    explicit MinimumLoserTree(T *thePlayer = nullptr, int theNumberOfPlayers = 0) {
        tree = nullptr;
        advance = nullptr;
        initialize(thePlayer, theNumberOfPlayers);
    }

    /*析构函数*/
    ~MinimumLoserTree() {
        delete[] tree;
        delete[] advance;
    }

    void initialize(T *thePlayer, int theNumberOfPlayers);//初始化
    [[nodiscard]] int getTheWinner() const { return tree[0]; };//输出当前的赢者
    void rePlay(int thePlayer, T newvalue);//重构
    void output() const;
private:
    int numberOfPlayers{};
    int *tree;// 记录内部结点,tree[0]是最终的赢者下标,不使用二叉树结点,因为父子关系都是通过计算得出
    int *advance;// 记录比赛晋级的成员
    T *player;//参与比赛的元素
    int lowExt{};//最底层外部结点的个数,2*(n-s)
    int offset{};//2*s-1
    void play(int, int, int);

    int winner(int x, int y) { return player[x] <= player[y] ? x : y; };//返回更小的元素下标
    int loser(int x, int y) { return player[x] <= player[y] ? y : x; };//返回更大的元素下标
};

template<class T>
void MinimumLoserTree<T>::initialize(T *thePlayer, int theNumberOfPlayers) {
    int n = theNumberOfPlayers;
    if (n < 2) {
        throw illegalParameterValue("must have at least 2 players");
    }
    player = thePlayer;
    numberOfPlayers = n;
    // 删除原来初始化的内存空间,初始化新的内存空间
    delete[] tree;
    delete[] advance;
    tree = new int[n + 1];
    advance = new int[n + 1];
    // 计算s
    int s;
    for (s = 1; 2 * s <= n - 1; s += s);//s=2^log(n-1)-1(常数优化速度更快),s是最底层最左端的内部结点

    lowExt = 2 * (n - s);
    offset = 2 * s - 1;

    for (int i = 2; i <= lowExt; i += 2)//最下面一层开始比赛
        play((i + offset) / 2, i - 1, i);//父结点计算公式第一条

    int temp = 0;
    if (n % 2 == 1) {//如果有奇数个结点,一定会存在特殊情况,需要内部节点和外部节点的比赛
        play(n / 2, advance[n - 1], lowExt + 1);
        temp = lowExt + 3;
    } else temp = lowExt + 2;//偶数个结点,直接处理次下层

    for (int i = temp; i <= n; i += 2)//经过这个循环,所有的外部结点都处理完毕
        play((i - lowExt + n - 1) / 2, i - 1, i);

    tree[0] = advance[1];//tree[0]是最终的赢者,也就是决赛的赢者

}

template<class T>
void MinimumLoserTree<T>::play(int p, int leftChild, int rightChild) {
    // tree结点存储相对较大的值,也就是这场比赛的输者
    tree[p] = loser(leftChild, rightChild);
    // advance结点存储相对较小的值,也就是这场比赛的晋级者
    advance[p] = winner(leftChild, rightChild);

    // 如果p是右孩子
    while (p % 2 == 1 && p > 1) {
        tree[p / 2] = loser(advance[p - 1], advance[p]);
        advance[p / 2] = winner(advance[p - 1], advance[p]);
        p /= 2;//向上搜索
    }
}

template<class T>
void MinimumLoserTree<T>::rePlay(int thePlayer, T newvalue) {
    int n = numberOfPlayers;
    if (thePlayer <= 0 || thePlayer > n) {
        throw illegalParameterValue("Player index is illegal");
    }

    player[thePlayer] = newvalue;

    int matchNode,//将要比赛的场次
    leftChild,//比赛结点的左孩子
    rightChild;//比赛结点的右孩子

    if (thePlayer <= lowExt) {//如果要比赛的结点在最下层
        matchNode = (offset + thePlayer) / 2;
        leftChild = 2 * matchNode - offset;
        rightChild = leftChild + 1;
    } else {//要比赛的结点在次下层
        matchNode = (thePlayer - lowExt + n - 1) / 2;
        if (2 * matchNode == n - 1) {//特殊情况,比赛的一方是晋级
            leftChild = advance[2 * matchNode];
            rightChild = thePlayer;
        } else {
            leftChild = 2 * matchNode - n + 1 + lowExt;//这个操作是因为上面matchNode计算中/2取整了
            rightChild = leftChild + 1;
        }
    }
    //到目前位置,我们已经确定了要比赛的场次以及比赛的选手

    //下面进行比赛重构,也就是和赢者树最大的不同,分两种情况
    if (thePlayer == tree[0]) {//当你要重构的点是上一场比赛的赢家的话,过程比赢者树要简化,简化之后只需要和父亲比较,不需要和兄弟比较
        for (; matchNode >= 1; matchNode /= 2) {
            int oldLoserNode = tree[matchNode];//上一场比赛的输者
            tree[matchNode] = loser(oldLoserNode, thePlayer);
            advance[matchNode] = winner(oldLoserNode, thePlayer);
            thePlayer = advance[matchNode];
        }
    } else {//其他情况重构和赢者树相同
        tree[matchNode] = loser(leftChild, rightChild);
        advance[matchNode] = winner(leftChild, rightChild);
        if (matchNode == n - 1 && n % 2 == 1) {//特殊情况
            // 特殊在matchNode/2后,左孩子是内部节点,右孩子是外部节点
            matchNode /= 2;
            tree[matchNode] = loser(advance[n - 1], lowExt + 1);
            advance[matchNode] = winner(advance[n - 1], lowExt + 1);
        }
        matchNode /= 2;
        for (; matchNode >= 1; matchNode /= 2) {
            tree[matchNode] = loser(advance[matchNode * 2], advance[matchNode * 2 + 1]);
            advance[matchNode] = winner(advance[matchNode * 2], advance[matchNode * 2 + 1]);
        }
    }
    tree[0] = advance[1];//最终胜者
}

template<class T>
void MinimumLoserTree<T>::output() const
{
    cout << "number of players = " << numberOfPlayers
         << " lowExt = " << lowExt
         << " offset = " << offset << endl;
    cout << "complete loser tree pointers are" << endl;
    for (int i = 1; i < numberOfPlayers; i++)
        cout << tree[i] << ' ';
    cout << endl;
}

#endif //_31LOSERTREE_MINIMUMLOSERTREE_H

MinimumLoserTree.cpp

/*
Project name :			_30winnerTree
Last modified Date:		2023年12月19日16点48分
Last Version:			V1.0
Descriptions:			最小输者树——测试函数
*/
#include "MinimumLoserTree.h"

void MinimumLoserTreeTest(){
    int n;
    cout << "Enter number of players, >= 2" << endl;
    cin >> n;
    if (n < 2)
    {cout << "Bad input" << endl;
        exit(1);}


    int *thePlayer = new int[n + 1];

    cout << "Enter player values" << endl;
    for (int i = 1; i <= n; i++)
    {
        cin >> thePlayer[i];
    }

    MinimumLoserTree<int> *w =
            new MinimumLoserTree<int>(thePlayer, n);
    cout << "The loser tree is" << endl;
    w->output();

    w->rePlay(2, 0);
    cout << "Changed player 2 to zero, new tree is" << endl;
    w->output();

    w->rePlay(3, -1);
    cout << "Changed player 3 to -1, new tree is" << endl;
    w->output();

    w->rePlay(7, 2);
    cout << "Changed player 7 to 2, new tree is" << endl;
    w->output();
    delete [] thePlayer;
    delete w;
}

loserTree.h

/*
Project name :			_30winnerTree
Last modified Date:		2023年12月19日16点48分
Last Version:			V1.0
Descriptions:			最小输者树——虚基类
*/

#ifndef _31LOSERTREE_LOSERTREE_H
#define _31LOSERTREE_LOSERTREE_H

template<class T>
class loserTree {
public:
    virtual ~loserTree() {}
    virtual void initialize(T *thePlayer, int number) = 0;
    virtual int getTheWinner() const = 0;
    virtual void rePlay(int thePLayer, T newvalue) = 0;
};

#endif //_31LOSERTREE_LOSERTREE_H

myExceptions.h

/*
Project name :			_30winnerTree
Last modified Date:		2023年12月18日16点28分
Last Version:			V1.0
Descriptions:			异常汇总
*/
#pragma once
#ifndef _MYEXCEPTIONS_H_
#define _MYEXCEPTIONS_H_
#include <string>
#include<iostream>
#include <utility>

using namespace std;

// illegal parameter value
class illegalParameterValue : public std::exception
{
public:
    explicit illegalParameterValue(string theMessage = "Illegal parameter value")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// illegal input data
class illegalInputData : public std::exception
{
public:
    explicit illegalInputData(string theMessage = "Illegal data input")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// illegal index
class illegalIndex : public std::exception
{
public:
    explicit illegalIndex(string theMessage = "Illegal index")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// matrix index out of bounds
class matrixIndexOutOfBounds : public std::exception
{
public:
    explicit matrixIndexOutOfBounds
            (string theMessage = "Matrix index out of bounds")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// matrix size mismatch
class matrixSizeMismatch : public std::exception
{
public:
    explicit matrixSizeMismatch(string theMessage =
    "The size of the two matrics doesn't match")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// stack is empty
class stackEmpty : public std::exception
{
public:
    explicit stackEmpty(string theMessage =
    "Invalid operation on empty stack")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// queue is empty
class queueEmpty : public std::exception
{
public:
    explicit queueEmpty(string theMessage =
    "Invalid operation on empty queue")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// hash table is full
class hashTableFull : public std::exception
{
public:
    explicit hashTableFull(string theMessage =
    "The hash table is full")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// edge weight undefined
class undefinedEdgeWeight : public std::exception
{
public:
    explicit undefinedEdgeWeight(string theMessage =
    "No edge weights defined")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};

// method undefined
class undefinedMethod : public std::exception
{
public:
    explicit undefinedMethod(string theMessage =
    "This method is undefined")
    {message = std::move(theMessage);}
    void outputMessage() {cout << message << endl;}
private:
    string message;
};
#endif

运行结果

"C:\Users\15495\Documents\Jasmine\prj\_Algorithm\Data Structures, Algorithms and Applications in C++\_31loserTree\cmake-build-debug\_31loserTree.exe"
Enter number of players, >= 2
8
Enter player values
4
6
5
9
8
2
3
7
The loser tree is
number of players  = 8 lowExt = 8 offset = 7
complete winner tree pointers are
1 3 7 2 4 5 8
Changed player 2 to zero, new tree is
number of players  = 8 lowExt = 8 offset = 7
complete winner tree pointers are
6 3 7 1 4 5 8
Changed player 3 to -1, new tree is
number of players  = 8 lowExt = 8 offset = 7
complete winner tree pointers are
6 2 7 1 4 5 8
Changed player 7 to 2, new tree is
number of players  = 8 lowExt = 8 offset = 7
complete winner tree pointers are
6 2 7 1 4 5 8

Process finished with exit code 0

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/259116.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

线性回归中的似然函数、最大似然估计、最小二乘法怎么来的(让你彻底懂原理)收官之篇

图1 图2 图3 图4 问1&#xff1a;为什么要引入似然函数&#xff1f; 在线性回归中引入似然函数是为了通过概率统计的方法对模型参数进行估计。简单来说&#xff0c;我们希望找到一组参数&#xff0c;使得我们观测到的数据在给定这组参数的情况下最有可能发生。 问:1&#xf…

js之零碎工具(四)

一、数组的去重 简单类型的去重 let arr [1, 2, 2, 3, 4, 4, 5]; let uniqueArr [...new Set(arr)]; console.log(uniqueArr); // 输出&#xff1a;[1, 2, 3, 4, 5]在这个例子中&#xff0c;我们首先创建了一个新的 Set 对象&#xff0c;并将数组 arr 作为参数传递给 Set 的…

深度学习中的张量维度

1 深度学习中的张量 在深度学习框架中&#xff0c;Tensor&#xff08;张量&#xff09;是一种数据结构&#xff0c;用于存储和操作多维数组。张量可以被视为一种扩展的矩阵&#xff0c;它可以具有任意数量的维度。 在深度学习中&#xff0c;张量通常被用来表示神经网络的输入…

管理类联考——数学——真题篇——按题型分类——充分性判断题——蒙猜——按题号

上来先找C&#xff1a;一个等号一个不等号型&#xff0c;一个定量一个定性型&#xff0c;取值范围有交集型&#xff0c;最后找选项需要联立型&#xff08;因为是否需要联立&#xff0c;不要判断&#xff0c;一般如十字交叉&#xff09;。一般也就3-4个C。详见这里 找完C后找AB&…

Java开发框架和中间件面试题(1)

1.什么是Spring框架&#xff1f; Spring是一种轻量级框架&#xff0c;旨在提高开发人员的开发效率以及系统的可维护性。 我们一般说的Spring框架就是Spring Framework,它是很多模块的集合&#xff0c;使用这些模块可以很方便的协助我们进行开发。这些模块是核心容器、数据访…

制造行业定制软件解决方案——工业信息采集平台

摘要&#xff1a;针对目前企业在线检测数据信号种类繁多&#xff0c;缺乏统一监控人员和及时处置措施等问题。蓝鹏测控开发针对企业工业生产的在线数据的集中采集分析平台&#xff0c;通过该工业信息采集平台可将企业日常各种仪表设备能够得到数据进行集中分析处理存储&#xf…

vmware离线安装docker-compose

vmware离线安装docker-compose 最近安装docker-compose&#xff0c;发现git取拉取&#xff0c;不是拒绝连接就是报443错误&#xff0c;或者其他错误 最后发现用包直接传上去好用&#xff0c;不用git拉取了 离线安装docker-compose 本文章给的docker-compose离线包&#xff0c;…

【超详细】基于单片机控制的十字道路口交通灯控制

目录 最终效果 一、设计任务 二、设计报告 1 设计说明 1.1功能分析 1.1.1整体系统功能分析 1.1.2显示状态功能分析 1.1.3设置状态功能分析 1.1.4紧急状态功能分析 1.2方案比选 1.2.1车辆LED数码管倒计时显示板块 1.2.2车辆信号灯显示板块 1.2.3行人信号灯显示板块 …

Web请求与响应

目录 Postman Postman简介 Postman的使用 请求 简单参数 实体参数 数组参数 集合参数 日期参数 Json参数 路径参数 响应 ResponseBody 统一响应结果 Postman Postman简介 postman是一款功能强大的网页调试与发送网页http请求的Chrome插件&#xff0c;常用于进行…

Zoho Mail:1600万企业用户的信赖之选

Zoho Mail和Workplace在线办公套件一起&#xff0c;已经成长为一个集邮箱、即时通讯、生产力工具于一身的非常全面的强大平台。经过数十年持续深入的研发投入&#xff0c;我们的产品可以很好地服务大型企业。 这是Zoho创始人斯瑞达•温布在Zoho Mail15周年之际发布的感想。 过去…

MSVC编译 openssl windows 库

开发需要在windows下集成 openssl 库&#xff0c;参考官方指导完成了编译&#xff1a;openssl/NOTES-WINDOWS.md at master openssl/openssl 不过&#xff0c;最后还是走了直接下载的捷径。 1. 安装 ActivePerl 需要在 ActiveState 注册账户&#xff0c;之后彼会提供具体的…

跨境卖家必看!TikTok带货经验分享,TikTok直播带货怎么做?

如今直播带货正发展得如火如荼&#xff0c;不少跨境人也纷纷做起了带货&#xff0c;其中TikTok带货的力量不容小觑&#xff0c;也已经成为了跨境电商运营非常火爆的营销方式&#xff0c;有很多朋友问龙哥TikTok带货怎么做&#xff0c;其实以龙哥这么多年的经验来看&#xff0c;…

VMware vSphere 虚拟机迁移按钮灰色解决方案

现象&#xff1a;在 vCenter Server 中右键单击虚拟机&#xff0c;然后单击迁移时&#xff0c;迁移选项将灰显。 原因&#xff1a;在虚拟机备份完成后&#xff0c;没有移除 vCenter Server 数据库 vpx_disabled_methods 表中的条目时&#xff0c;可能会出现此问题。 解决方案&a…

保姆月嫂企业网站建设的效果如何

保姆月嫂月子中心成为很多家庭的选择&#xff0c;随着人们生活质量提升及消费升级&#xff0c;围绕母婴行业、居家场景的服务需求度越来越多&#xff0c;而市场同行竞争压力下&#xff0c;也促使着各家保姆月嫂品牌需要通过多种方式增长破圈。 虽然保姆月嫂的市场需求度较高&am…

【Python炫酷系列】祝考研的友友们金榜题名吖(完整代码)

文章目录 环境需求完整代码详细分析系列文章环境需求 python3.11.4及以上版本PyCharm Community Edition 2023.2.5pyinstaller6.2.0(可选,这个库用于打包,使程序没有python环境也可以运行,如果想发给好朋友的话需要这个库哦~)【注】 python环境搭建请见:https://want595.…

谷达冠楠科技:现在开抖音小店怎么样前景好不好

随着互联网的发展&#xff0c;电商平台已经成为了人们生活中不可或缺的一部分。而近年来&#xff0c;抖音作为短视频平台的领军者&#xff0c;也推出了自己的电商功能——抖音小店。那么&#xff0c;现在开抖音小店的前景如何呢? 首先&#xff0c;我们需要了解抖音的用户基数。…

CountDownLatch和Semaphore的区别?

CountDownLatch和Semaphore都是在Java中用于多线程协同的工具&#xff0c;但它们有一些重要的区别。 CountDownLatch&#xff1a; 用途&#xff1a; 主要用于等待一个或多个线程完成操作&#xff0c;它的计数器只能被减少&#xff0c;不能被增加。计数&#xff1a; 初始化时需…

致深空中最遥远的你

"旅行者1号" 的在11月14日飞行数据系统陷入了自动重复的状态&#xff0c;飞行数据系统的电信单元开始重复发回1和0模式就像陷入循环一样&#xff0c;旅行者1号目前离地球约240亿公里发回的消息需要大约22.5小时的传播时间。NASA分析故障来官探测器上的两台计算机&…

攻防世界-web-ics07

1. 题目描述 工控云管理系统项目管理页面解析漏洞 打开链接&#xff0c;是这样的一个界面 我们点击项目管理 可以看到&#xff0c;这里有一个查询界面&#xff0c;还有个view-source的链接&#xff0c;我们点击下view-source&#xff0c;可以看到这里面共有三段php代码 第一段…

Redis是单线程还是多线程,为什么快?

1.Redis是单线程模型还是多线程模型&#xff1f; 在redis6.X版本之前&#xff0c;属于彻彻底底的单线程模型&#xff0c;redis在解析客户端命令和读写数据的操作都是由一个单线程来解决的。 而redis6.X版本后&#xff0c;引入了多线程&#xff0c;但是只作用于解析客户端的命令…
最新文章