9.7 堆
9.7 堆
http://codeup.hustoj.com/contest.php?cid=100000616
A 算法10-10,10-11:堆排序

题目解析
向下调整downAdjust函数构建最大堆,则heapSort从小到大排序。
代码
#include <cstdio>
#include <algorithm>
#define maxn 100005
using namespace std;
int n;
int heap[maxn];
void downAdjust(int low, int heigh) {
int f = low; //父结点
int c = 2 * f; //左孩子
while (c <= heigh) { //左孩子存在
if (c + 1 <= heigh) { //右孩子存在
if (heap[c + 1] > heap[c]) c += 1;
}
if (heap[c] > heap[f]) {
swap(heap[f], heap[c]);
f = c; //保持father为欲更改结点
c = 2 * f;
} else break;
}
}
void createHeap() {
for (int i = n / 2; i >= 1; i--) {
downAdjust(i, n);
}
}
void heapSort() {
createHeap();
for (int i = n; i > 1; i--) {
swap(heap[i], heap[1]);
downAdjust(1, i - 1);
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &heap[i]);
}
heapSort();
for (int i = 1; i <= n; i++) {
printf("%d ", heap[i]);
}
printf("\n");
return 0;
}
B 序列合并

题目解析
自己的代码时间超限,晚上找的AC代码:https://www.cnblogs.com/heyour/p/12711821.html
大致思路如下:
首先,取a[]数组中的最小元素,也就是a[0],分别加上b[i](0<=i<n),并放入优先队列中。那么可以确定,此时优先队列队首的元素,也即a[0]+b[0]的值就是最小的,可以输出,并将a[1]+b[0]输入优先队列,依次类推,直到输出了n个数为止。
代码(时间超限)
#include <queue>
#include <cstdio>
#define maxn 1000005
using namespace std;
int main() {
priority_queue<int, vector<int>, greater<int>> q;
int a[maxn];
int n, b;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (int i = 0; i < n; i++) {
scanf("%d", &b);
for (int j = 0; j < n; j++) {
q.push(a[j] + b);
}
}
for (int i = 0; i < n && !q.empty(); i++) {
printf("%d", q.top());
q.pop();
if (i < n - 1) printf(" ");
else printf("\n");
}
return 0;
}
代码(AC)
#include<bits/stdc++.h>
using namespace std;
const int MAX=1e5+2;
struct Node{
int index, sum;
bool operator < (const Node &t) const{
return sum > t.sum; //优先队列表示按sum的大小排列
}
};
int main(){
int i, n, a[MAX], b[MAX];
Node temp, now;
priority_queue<Node> q;
while(cin >> n){
for(i=0; i<n; i++) scanf("%d", &a[i]);
for(i=0; i<n; i++){
scanf("%d", &b[i]);
temp.index = 0;
temp.sum = b[i] + a[temp.index]; //index表示a[]中的第几个数字
q.push(temp);
}
for(i=0; i<n; i++){
now = q.top();
q.pop();
if(now.index+1 < n){
temp.index = now.index + 1;
temp.sum = now.sum - a[now.index] + a[temp.index];
q.push(temp);
}
printf("%d%c", now.sum, i==n-1?'\n':' ');
}
}
return 0;
}
本文作者:Joey-Wang
本文链接:https://www.cnblogs.com/joey-wang/p/14541187.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步