Files
python/TangDou/LuoGuBook/L16_1.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

49 lines
1.6 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 260;
int value[N]; //记录该子树获胜者的实力值
int winner[N];//记录该子树获胜者
//本题n的概念很奇葩不是n个国家是2^n个国家~,比如n=3,就是2^3个国家即8个国家。
int n;
//函数定义计算x结点的获胜者
void dfs(int x) {
//叶子结点
if (x >= (1 << n)) return;//啥也不用干,因为手动填充干净了,递归出口
//填充左子树,填充右子树
dfs(2 * x), dfs(2 * x + 1);
//左结点值,右结点值
int lvalue = value[2 * x], rvalue = value[2 * x + 1];
//pk,谁大就更新成谁的
if (lvalue > rvalue) value[x] = lvalue, winner[x] = winner[2 * x];
else value[x] = rvalue, winner[x] = winner[2 * x + 1];
}
/**
测试用例:
3
4 2 3 1 10 5 9 7
*/
int main() {
cin >> n;
//填充叶子结点共2^n个
for (int i = 0; i < (1 << n); i++) {//完美二叉树结点个数 2^n
//计算出叶子结点的下标,数组下标从1开始
int k = i + (1 << n); // 前面预留了1~ 2^n-1个因为整个完美二叉树的结点个数是2^n-1个。
cin >> value[k]; //读入各个结点的能力值
winner[k] = i + 1; //叶子结点的获胜方就是自己国家的编号
}
//从根结点开始遍历,填充整个世界杯的成绩结果树
//之所以可以使用递归,是因为底边的边界是已知的,可以通过底边的对比获取到倒数第二行的...
dfs(1);
//找亚军
cout << ((value[2] > value[3]) ? winner[3] : winner[2]) << endl;
return 0;
}