P4715 【深基16.例1】淘汰赛 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
就是将二叉树的叶子节点给出了,让我们模拟找到根
顺序表:
数组做法:
#include <iostream>
using namespace std;
int n, a[150], id[150]; //a存能力,id存编号
int main()
{
cin >> n;
int t = 1;
while(n -- )
{
t *= 2;
}
n = t;
for(int i = 1; i <= n; i ++ )
{
id[i] = i;
cin >> a[i];
}
while(n != 1)
{
// for(int i = 1; i <= n; i ++ ) cout << a[i] << ' ';
// cout << endl;
int cnt = 1;
if(n == 2)
{
if(a[1] > a[2])
{
cout << id[2] << endl;
}
else
{
cout << id[1] << endl;
}
break;
}
for(int i = 1; i <= n; i += 2)
{
if(a[i] > a[i + 1])
{
a[cnt] = a[i];
id[cnt ++] = id[i];
}
else
{
a[cnt] = a[i + 1];
id[cnt ++] = id[i + 1];
}
}
n /= 2;
}
return 0;
}
队列做法:就是每次取两个比较,然后再放在队尾
#include <iostream>
#include <queue>
using namespace std;
int n;
queue<pair<int, int>> q;
int main()
{
cin >> n;
n = 1 << n; //2^n
for(int i = 1; i <= n; i ++ )
{
int x;
cin >> x;
q.push({i, x});
}
// cout << q.size() << endl;
while(q.size() != 2)
{
auto a = q.front();
q.pop();
auto b = q.front();
q.pop();
if(a.second > b.second )
{
q.push(a);
}
else
{
q.push(b);
}
if(q.size() == 2)
{
}
}
auto a = q.front();
q.pop();
auto b = q.front();
q.pop();
if(a.second > b.second )
{
cout << b.first << endl;
}
else
{
cout << a.first << endl;
}
return 0;
}
对顶栈写法:可惜re了
#include <iostream>
#include <stack>
using namespace std;
int n;
stack<pair<int, int>> q, tmp;
int main()
{
cin >> n;
n = 1 << n; //2^n
for(int i = 1; i <= n; i ++ )
{
int x;
cin >> x;
q.push({i, x});
}
// cout << q.size() << endl;
while(tmp.size() != 2 && q.size() != 2)
{
while(q.size())
{
auto a = q.top();
q.pop();
auto b = q.top();
q.pop();
if(a.second > b.second)
{
tmp.push(a);
}
else
{
tmp.push(b);
}
}
while(tmp.size())
{
auto a = tmp.top();
tmp.pop();
auto b = tmp.top();
tmp.pop();
if(a.second > b.second)
{
q.push(a);
}
else
{
q.push(b);
}
}
}
if(tmp.size() == 2)
{
auto a = tmp.top();
tmp.pop();
auto b = tmp.top();
tmp.pop();
if(a.second > b.second)
{
cout << b.first << endl;
}
else
{
cout << a.first << endl;
}
}
if(q.size() == 2)
{
auto a = q.top();
q.pop();
auto b = q.top();
q.pop();
if(a.second > b.second)
{
cout << b.first << endl;
}
else
{
cout << a.first << endl;
}
}
return 0;
}