用c++写代码 如果一个长度为n的序列恰好包含一次从1到n的所有数字则称为排列。比如3142、1、21是排列但是121、01不是。 给你一个数字n你需要构造一个长度为n的排列p满足: 1对于每个元素pi至少有一
#include
using namespace std;
void printInterestingPermutation(int n) { if (n <= 2) { cout << -1 << endl; return; }
vector<int> permutation;
for (int i = 1; i <= n; i++) {
permutation.push_back(i);
}
for (int i = 0; i < n - 1; i++) {
if (permutation[i] == i + 1) {
swap(permutation[i], permutation[i + 1]);
}
}
if (permutation[n - 1] == n) {
swap(permutation[n - 1], permutation[n - 2]);
}
for (int i = 0; i < n; i++) {
cout << permutation[i] << " ";
}
cout << endl;
}
int main() { int t; cin >> t;
while (t--) {
int n;
cin >> n;
printInterestingPermutation(n);
}
return 0;
原文地址: http://www.cveoy.top/t/topic/hV1k 著作权归作者所有。请勿转载和采集!