一:胜者树和败者树都是完全二叉树,是树形选择排序的一种变型。每个叶子结点相当于一个选手,每个中间结点相当于一场比赛,每一层相当于一轮比赛。
二:不同的是,胜者树的中间结点记录的是胜者的标号;而败者树的中间结点记录的败者的标号。
三:胜者树与败者树可以在log(n)的时间内找到最值。任何一个叶子结点的值改变后,利用中间结点的信息,还是能够快速地找到最值。在k路归并排序中经常用到
#include <iostream>
using namespace std;
const int MIN = (1<<31);
const int LEN = 8;
int losT[LEN+1]; // 败者树里存储的是a数组的索引
int a[LEN+1] = {4, 7, 2, 14, 45, 23, 9, 82, MIN};
inline void adjust(int idx){
int pIdx = (idx+LEN)/2; // 得到父节点索引
while(pIdx > 0){
if(a[idx] > a[losT[pIdx]]){
swap(losT[pIdx], idx);
}
pIdx = pIdx/2;
}
losT[0] = idx;
}
void build(){
for(int i = 0; i <= LEN; i++){
losT[i] = LEN;
}
for(int i = 0; i < LEN; i++){
adjust(i);
}
}
int main(int argc, char* argv[])
{
build();
cout << losT[0] << " " << a[losT[0]] << endl;
a[losT[0]] = 5;
adjust(losT[0]);
cout << losT[0] << " " << a[losT[0]] << endl;
return 0;
}