文章目錄
- Swap and Reverse
- 題意:
- 題解:
- 代碼:
Swap and Reverse
題意:
給定一個長度為n的正整數數組,給定k。可以進行任意次一下操作
- 選定 i i i,交換 a i a_{i} ai?和 a i + 2 a_{i+2} ai+2?的值
- 選定 i i i,對區間 [ a i , a i + k ? 1 ] [a_{i},a_{i+k-1}] [ai?,ai+k?1?]進行翻轉
題解:
- 對于操作一:只能交換下標奇偶性相同的值。
- 對于操作二:若k為奇數,也只能交換下標奇偶性相同的值,若k為偶數,結合操作一則可以任意交換兩個相鄰的元素,所以對于所有位置元素可以任意交換。
代碼:
#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;const int N = 1e5+10;
typedef long long ll;char str[N];void sovle() {int n, k;cin >> n >> k;cin >> str;
//當k為奇數時,回用到進行分下標為奇數和偶數排序vector<char> a, b;if (k % 2 == 0) {sort(str, str + n);for (int i = 0; i < n; i++)cout << str[i];}else {//只需要分奇數和偶數排序,就能涵蓋所有點for (int i = 0; i <= n - 1; i += 2) a.push_back(str[i]);for (int i = 1; i <= n - 1; i += 2) b.push_back(str[i]);sort(a.begin(), a.end());sort(b.begin(), b.end());//交叉打印int l1 = 0, l2 = 0;for (int i = 1; i <= n; i++) {if (i % 2) {cout << a[l1];l1++;}else {cout << b[l2];l2++;}}}cout << endl;
}int main()
{ios::sync_with_stdio(false);cin.tie(0);int t;cin >> t;while (t--) {sovle();}return 0;
}