输入描述
Input Description
二叉树的节点数N和N个节点(按层输入)
输出描述
Output Description
YES或NO
样例输入
Sample Input
样例输入1
3
1 4 9
样例输入2
3
6 4 9
样例输出
Sample Output
样例输出1
YES
样例输出2
NO
数据范围及提示
Data Size & Hint
对于20%的数据 N≤20
对于50%的数据 N≤1000
对于100%的数据 N≤50000,每个节点≤10000
根据小根堆的性质:父节点的左右子节点的值小于父节点的值
奉上AC代码:
#include<bits/stdc++.h>
using namespace std;
int n,a[1000000];
bool tp;
int main()
{
cin>>n;
memset(a,0x7f,sizeof(a));
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++){
int l=i*2,r=i*2+1;
if(a[l]<a[i]){tp=1;break;}
else if(a[r]<a[i]){tp=1;break;}
}if(tp==1) cout<<"NO";
else cout<<"YES";
}
题目描述
Description
给定N(N≤500,000)和N个整数(较有序),将其排序后输出。
输入描述
Input Description
N和N个整数
输出描述
Output Description
N个整数(升序)
样例输入
Sample Input
5
12 11 10 8 9
样例输出
Sample Output
8 9 10 11 12
数据范围及提示
Data Size & Hint
对于33%的数据 N≤10000
对于另外33%的数据 N≤100,000 0≤每个数≤1000
对于100%的数据 N≤500,000 0≤每个数≤2*10^9
堆排序模板题:
奉上AC代码:
1.堆排序1


#include<bits/stdc++.h> using namespace std; int q,heap[500005]; void heapify(int num[],int i,int size){ int left_child=2*i; int right_child=2*i+1; int maxn=i; if(left_child<size&&num[left_child]>num[maxn]) maxn=left_child; if(right_child<size&&num[right_child]>num[maxn]) maxn=right_child; if(maxn!=i){ swap(num[i],num[maxn]); heapify(num,maxn,size); } } int buildheap(int num[],int n){ int heap_size=n; for(int i=heap_size/2;i;i--) heapify(num,i,heap_size); return heap_size; } void heapsort(int num[],int n){ int heap_size=buildheap(num,n); while(heap_size>1){ swap(num[1],num[--heap_size]); heapify(num,1,heap_size); } } int main() { cin>>q; for(int i=1;i<=q;i++) cin>>heap[i]; heapsort(heap,q+1); for(int i=1;i<=q;i++) cout<<heap[i]<<" "; return 0; }
2.堆排序2
根据插入以及弄出两种操作


#include<iostream> using namespace std; int heap[500010],heap_size; void put(int d) { int now, next; heap[++heap_size] = d; now = heap_size; while(now > 1) { next = now >> 1; if(heap[now] >= heap[next]) break; swap(heap[now], heap[next]); now = next; } } int get() { int now=1, next, res= heap[1]; heap[1] = heap[heap_size--]; while(now * 2 <= heap_size) { next = now * 2; if (next < heap_size && heap[next + 1] < heap[next]) next++; if (heap[now] <= heap[next]) break; swap(heap[now], heap[next]); now = next; } return res; } int main() { int n,x; cin>>n; for(int i=1;i<=n;i++){ cin>>x; put(x); }for(int i=1;i<=n;i++){ cout<<get()<<" "; } return 0; }
3.当然,也可以使用STL水过去
#include<bits/stdc++.h>
using namespace std;
int n;
priority_queue<int ,vector<int>,greater<int> >heap;
int main()
{
cin>>n;
for(int i=1;i<=n;i++){
int x;
cin>>x;
heap.push(x);
}for(int i=1;i<=n;i++){
cout<<heap.top()<<" ";
heap.pop();
}
return 0;
}