跳到正文

题解

题解:CF2121D 1709

Tomwsc约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年6月24日
收录
2025年12月12日
更新
2026年10月9日
篇幅
约 4 分钟
获赞
4
题目
CF2121D

版本

  1. v1当前

CF2121D 1709 题解

思路

考虑先分别将 aa 数组和 bb 数组冒泡排序,然后对于每一个 1≤i≤n1\le i\le n 检查是否满足 ai<bia_i< b_i,若不满足则令答案加一并交换 aia_i 和 bib_i。容易得到这样的最坏次数为 n×(n+1)+n<1709n\times (n+1)+n<1709,所以不会超过限制。

那为什么对于递增的 aa 和 bb 数组,可以直接交换 aia_i 和 bib_i?分类讨论即可:

  • 若 ai<bia_i<b_i 且 ai+1>bi+1a_{i+1}>b_{i+1},则需交换 ai+1a_{i+1} 与 bi+1b_{i+1},因为 ai+1>bi+1>bi>aia_{i+1}>b_{i+1}>b_i>a_i,所以交换后的 aa,bb 数组一定仍然单调递增。
  • 若 ai>bia_i>b_i 且 ai+1<bi+1a_{i+1}<b_{i+1},则需交换 aia_{i} 与 bib_{i},因为 bi+1>ai+1>ai>bib_{i+1}>a_{i+1}>a_i>b_i,所以交换后的 aa,bb 数组一定仍然单调递增。

剩下的情况就没什么好讨论的了。

代码

C++
// Problem: D. 1709
// Contest: Codeforces - Codeforces Round 1032 (Div. 3)
// URL: https://codeforces.com/problemset/problem/2121/D
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
#define int long long
#define inf (1ll << 62)
#define regint register int
#define pb push_back
#define mp make_pair
#define PII pair<int , int>
#define fi first
#define se second
using namespace std;
const int MAXN = 2e5 + 10;

inline void solve() {
	int n , cnt = 0;
	cin >> n;
	vector<int>a(n + 1) , b(n + 1);
	vector<PII>ans;
	for(regint i = 1;i <= n;i ++) cin >> a[i];
	for(regint i = 1;i <= n;i ++) cin >> b[i];
	for(regint i = 1;i <= n;i ++) {
		for(regint j = 1;j < n - i + 1;j ++) {
			if(a[j] > a[j + 1]) {
				swap(a[j] , a[j + 1]);
				ans.pb(mp(1 , j));
				cnt ++;
			}
			if(b[j] > b[j + 1]) {
				swap(b[j] , b[j + 1]);
				ans.pb(mp(2 , j));
				cnt ++;
			}
		}
	}
	// sort(a.begin() + 1 , a.end());
	// sort(b.begin() + 1 , b.end());
	for(regint i = 1;i <= n;i ++) {
		if(a[i] > b[i]) {
			ans.pb(mp(3 , i));
			cnt ++;
			// cout << 3 << " " << i << '\n';
		}
	}
	cout << cnt << '\n';
	for(auto i : ans) cout << i.fi << " " << i.se << '\n';
	return;
}

signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int t = 1;
	cin >> t;
	while(t --) {
		solve();
	}
	return 0;
}
原文