用C++解决以下问题:给出一个长度为n的数组 a_1a_2a_3an 求一个字典序最小的1~n的排列P 使得原数组重新排列成a_P_1a_P_2a_P_3a_P_n后每一个前缀的平均数都大于等于 0 。
首先,我们需要找到一个字典序最小的1~n的排列P。我们可以使用C++的标准库函数std::sort来对数组进行排序,然后使用std::vector来保存排列P。
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n;
std::cout << "Enter the size of the array: ";
std::cin >> n;
std::vector<int> arr(n);
std::cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
std::vector<int> P(n);
for (int i = 0; i < n; i++) {
P[i] = i + 1;
}
std::sort(P.begin(), P.end());
std::cout << "Permutation P: ";
for (int i = 0; i < n; i++) {
std::cout << P[i] << " ";
}
std::cout << std::endl;
return 0;
}
接下来,我们需要重新排列原数组,使得每个前缀的平均数都大于等于0。我们可以使用C++的std::partial_sort函数来对数组的前缀进行排序。
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n;
std::cout << "Enter the size of the array: ";
std::cin >> n;
std::vector<int> arr(n);
std::cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
std::cin >> arr[i];
}
std::vector<int> P(n);
for (int i = 0; i < n; i++) {
P[i] = i + 1;
}
std::sort(P.begin(), P.end());
std::cout << "Permutation P: ";
for (int i = 0; i < n; i++) {
std::cout << P[i] << " ";
}
std::cout << std::endl;
std::partial_sort(arr.begin(), arr.end(), arr.begin() + 1, arr.end());
std::cout << "Rearranged array: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
这样,我们就得到了满足条件的排列P和重新排列后的数组。注意,这里的平均数指的是前缀的平均数,即从第一个元素开始到当前位置的平均数
原文地址: https://www.cveoy.top/t/topic/iQvI 著作权归作者所有。请勿转载和采集!