您的位置:首页 > 其它

Heap_堆_2018_2_20

2018-02-20 09:04 169 查看
A (binary) heap is an array that can be viewed as a nearly complete binary tree. In this problem, we are talking about max-heaps.
A max-heap holds the property that for each node than the root, it’s key is no greater than its parent’s. Upon this we further require that for every node that has two children, key of any node in the subtree rooted at its left child should be less than that of any node in the subtree rooted at its right child.
Any array can be transformed into a max-heap satisfying the above requirement by modifying some of its keys. Your task is find the minimum number of keys that have to be modified.
Input The input contains a single test case. The test case consists of nonnegative integers distributed on multiple lines. The first integer is the height of the heap. It will be at least 1 and at most 20. Then follow the elements of the array to be transformed into a heap described above, which do not exceed 109. Modified elements should remain integral though not necessarily nonnegative.
Output Output only the minimum number of elements (or keys) that have to be modified.
Sample Input
3
1
3 6
1 4 3 8
Sample Output
4
Hint
1                 10
/ \               /  \
3   6    =====>   3    9
/ \ / \           / \  / \
1 4 3 8           1 2  4 8
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

vector<int> v;
vector<int> vv;
int cnt=0,delta;
void dfs(int x){
if(2*x+1<cnt)dfs(2*x+1);
if(2*x+2<cnt){
delta++;
dfs(2*x+2);
}
v[x]-=delta;
if(vv.empty()||v[x]>=vv.back())
vv.push_back(v[x]);
else *upper_bound(vv.begin(),vv.end(),v[x])=v[x];
}
int main(){
int n;
scanf("%d",&n);
int x;
while(~scanf("%d",&x))
v.push_back(x);
cnt=v.size();
dfs(0);
printf("%d\n",cnt-vv.size());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: