社区讨论
用手写堆排序A了,但有点小问题
P1177【模板】排序参与者 5已保存回复 4
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 4 条
- 当前快照
- 1 份
- 快照标识符
- @m0c7ut3f
- 此快照首次捕获于
- 2024/08/27 17:19 2 年前
- 此快照最后确认于
- 2025/11/04 22:16 4 个月前
CPP
#include <bits/stdc++.h>
using namespace std;
int n, tot = n;
int a[200010], b[100010];
void adjust(int i) {
int k;
if (i > n)
return ;
if (a[i * 2] > a[i * 2 + 1]) {
k = i * 2;
} else
k = i * 2 + 1;
if (a[i] > a[k])
return ;
else {
swap(a[i], a[k]);
adjust(k);
}
}
deque<int>q;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
for (int i = n / 2; i >= 1; i--) {
adjust(i);
}
for (int i = 1; i <= n; i++) {
q.push_back(a[1]);
swap(a[tot], a[1]);
tot--;
adjust(1);
}
while (!q.empty()) {
printf("%d ", q.back());
q.pop_back();
}
return 0;
}
我的tot变量初始值为0,我那里tot--,又调用a[tot],它不会数组越界吗
回复
共 4 条回复,欢迎继续交流。
正在加载回复...