Codeforces Global Round 11 D. Unshuffling a Deck(构造/相邻逆序对)

题目链接:https://codeforces.com/contest/1427/problem/D

题意

给出一个大小为 \(n\) 的排列,每次操作可以将 \(n\) 个数分为 \(1 \sim n\) 个非空连续份,然后将对称的份两两交换,试给出在 \(n\) 次操作内将排列排为升序的操作过程。

题解

  1. 找到值相差为 \(1\) 的逆序对:\(i<j\)\(a_i = a_j + 1\)
  2. 将已为升序的数视为一个整体,找到 \(t\) 满足 \(i \le t < j\)\(a_t > a_{t+1}\)
  3. 分为 \(4\) 份,\(D_1=[a_1,a_2,\dots,a_{i-1}],\ D_2=[a_i,a_{i+1},\dots, a_t],\ D_3=[a_{t+1},a_{t+2},\dots, a_j],\ D_4=[a_{j+1},a_{j+2},\dots, a_n]\)
  4. 将对称组交换,转至步骤 \(1\)

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int n;
	cin >> n;
	vector<int> a(n), pos(n);
	for (int i = 0; i < n; i++) {
		cin >> a[i];
		--a[i];
	}
	vector<vector<int>> ans;
	while (not is_sorted(a.begin(), a.end())) {
		for (int i = 0; i < n; i++) {
			pos[a[i]] = i;
		}
		//1
		for (int i = 1; i < n; i++) {
			if (pos[i] < pos[i - 1]) {
				//2
				int l = pos[i];
				int r = pos[i - 1];
				int mid = l;
				while (a[mid + 1] == a[mid] + 1) ++mid;
				//3
				ans.push_back({l, mid - l + 1, r - mid, n - r - 1});
				//4
				vector<int> b;
				for (int i = r + 1; i < n; i++) b.push_back(a[i]);
				for (int i = mid + 1; i < r + 1; i++) b.push_back(a[i]);
				for (int i = l; i < mid + 1; i++) b.push_back(a[i]);
				for (int i = 0; i < l; i++) b.push_back(a[i]);
				a.swap(b);
				break;
			}
		}
	}
	cout << ans.size() << "\n";
	for (auto &v : ans) {
		//每份非空
		while (v.back() == 0) v.pop_back();
		while (v.front() == 0) v.erase(v.begin());
		cout << v.size() << "\n";
		for (int i = 0; i < int(v.size()); i++) {
			cout << v[i] << " \n"[i == int(v.size()) - 1];
		}
	}
	return 0;
}
posted @ 2020-10-14 00:50  Kanoon  阅读(228)  评论(0编辑  收藏  举报