题解:CF2121D 1709

· · 题解

CF2121D 1709 题解

思路

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

那为什么对于递增的 a 和 b 数组,可以直接交换 a_i 和 b_i?分类讨论即可:

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

代码

// 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;
}