赢者树代码
时间: 2023-07-23 16:16:41 浏览: 37
赢者树(Winner Tree)是一种树形数据结构,用于在一系列元素中找到最小值或最大值。下面是C++实现赢者树的代码:
```cpp
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int n,m;
int a[maxn];
int tree[maxn];
void build_tree(){
for(int i=n;i<2*n;i++){
tree[i]=i-n;
}
for(int i=n-1;i;i--){
tree[i]=a[tree[i<<1]]<a[tree[i<<1|1]]?tree[i<<1]:tree[i<<1|1];
}
}
void update(int i){
i+=n;
while(i){
int j=i^1;
tree[i]=a[tree[i]]<a[tree[j]]?tree[i]:tree[j];
i>>=1;
}
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
build_tree();
scanf("%d",&m);
while(m--){
int op,x,y;
scanf("%d%d",&op,&x);
if(op==1){
scanf("%d",&y);
a[x]=y;
update(x);
}
else printf("%d\n",tree[1]);
}
return 0;
}
```
在上述代码中,build_tree函数用于构建赢者树,update函数用于更新某个叶子节点的值并维护整个树。在主函数中,首先读入n个数,然后构建赢者树,最后进行m次操作,如果是查询操作,则输出当前最小值,如果是修改操作,则更新对应叶子节点的值并重新维护整个树。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)