AcWing 1618. 结绳
原题链接
中等
作者:
_T_
,
2021-11-05 22:24:32
,
所有人可见
,
阅读 279
C++ 代码
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<algorithm>
#include<stack>
using namespace std;
int n;
int h[200000000], SIZE = 0;
stack<int> res;
void down(int u)
{
int t = u;
if (u * 2 <= SIZE && h[u * 2] < h[t]) t = u * 2;
if (u * 2 + 1 <= SIZE && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
if (u != t)
{
swap(h[u], h[t]);
down(t);
}
}
void up(int u)
{
while (u / 2 && h[u] < h[u / 2])
{
swap(h[u], h[u / 2]);
u >>= 1;
}
}
int main()
{
long long sum = 0;
scanf("%d",&n);
if (n == 1) {
printf("0");
return 0;
}
for (int i = 1; i <=n; i++) {
scanf("%d",&h[i]);
}
SIZE = n;
for (int i = n/2; i >= 1; i--) {
down(i);
}
while (SIZE!=1) {
//int x=q.front();q.pop();
int x = h[1];
h[1] = h[SIZE];
SIZE--;
down(1);
//int y=q.front();q.pop();
int y = h[1];
h[1] = h[SIZE];
SIZE--;
down(1);
//q.push(x + y);
h[++SIZE] = x + y>>1;
up(SIZE);
res.push(x + y>>1);
//sum += x + y;//WPL
}
cout << res.top() << endl;
return 0;
}