题解7
2025-04-30 15:15:34
发布于:江苏
10阅读
0回复
0点赞
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main() {
int n;
cin >> n;
vector<double> heights(n);
for (int i = 0; i < n; ++i) {
cin >> heights[i];
}
// 找到最高和第二高的同学的位置
int max1_pos = 0, max2_pos = 0;
for (int i = 1; i < n; ++i) {
if (heights[i] > heights[max1_pos]) {
max2_pos = max1_pos;
max1_pos = i;
} else if (heights[i] > heights[max2_pos] || max1_pos == max2_pos) {
max2_pos = i;
}
}
// 交换最高和最左边
swap(heights[max1_pos], heights[0]);
// 交换第二高和最右边,但要确保第二高没有被交换到最左边
if (max2_pos == 0) {
max2_pos = max1_pos;
}
swap(heights[max2_pos], heights[n - 1]);
// 输出结果
for (int i = 0; i < n; ++i) {
cout << fixed << setprecision(2) << heights[i];
if (i != n - 1) {
cout << " ";
}
}
cout << endl;
return 0;
}
这里空空如也
有帮助,赞一个