题解:P14029 【MX-X20-T3】「FAOI-R7」重排序列(update)

· · 题解

Sol

在以下操作前,先令 a_i\gets a_i\bmod m,b_i\gets b_i \bmod m。

将 a 排序,将 b 插入到 set 里,设这个 set 为 s。

从前往后做,找到 s 中可以与 a_i 相加不取模的最大数,可以用 lower_bound 找到,如果找不到那么任意选一个即可。

贪心策略显然不劣。

笑点解析:出题人受启发的题目是 Match, Mod, Minimize,结果出了一个和 Match, Mod, Minimize 2 一样的题目。

Code

/* Author: incra */
#include <bits/stdc++.h>
#define x first
#define y second
#define pb push_back
#define pf push_front
#define desktop "C:\\Users\\incra\\Desktop\\"
#define IOS ios :: sync_with_stdio (false),cin.tie (0),cout.tie (0)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair <int,int> PII;
const int dx[] = {1,0,-1,0},dy[] = {0,-1,0,1};
template <typename T1,typename T2> bool tomax (T1 &x,T2 y) {
    if (y > x) return x = y,true;
    return false;
}
template <typename T1,typename T2> bool tomin (T1 &x,T2 y) {
    if (y < x) return x = y,true;
    return false;
}
LL power (LL a,LL b,LL p) {
    LL ans = 1;
    while (b) {
        if (b & 1) ans = ans * a % p;
        a = a * a % p;
        b >>= 1;
    }
    return ans;
}
int fastio = (IOS,0);
#define endl '\n'
#define puts(s) cout << (s) << endl
const int N = 200010;
int n,m;
PII a[N];
int b[N];
int ansv[N];
void mian () {
    cin >> n >> m;
    for (int i = 1;i <= n;i++) cin >> a[i].x,a[i].x %= m,a[i].y = i;
    sort (a + 1,a + n + 1);
    set <PII> s;
    for (int i = 1;i <= n;i++) {
        cin >> b[i];
        s.insert ({b[i] % m,i});
    }
    LL ans = 0;
    for (int i = 1;i <= n;i++) {
        auto it = s.lower_bound ({m - a[i].x,0});
        // cout << it -> y << "====" << endl;
        if (it == s.begin ()) {
            ans += (a[i].x + s.begin () -> x) % m;
            ansv[a[i].y] = s.begin () -> y;
            s.erase (s.begin ());
        }
        else {
            it--;
            ans += (a[i].x + (it -> x)) % m;
            ansv[a[i].y] = it -> y;
            s.erase (it);
        }
    }
    cout << ans << endl;
    for (int i = 1;i <= n;i++) cout << b[ansv[i]] << ' ';
    cout << endl;
}
int main () {
    int T = 1;
    cin >> T;
    while (T--) mian ();
    return 0;
}