题解:P12386 [蓝桥杯 2023 省 Python B] 混乱的数组

· · 题解

前提概要

使得 A 中恰好有 x 对 i, j 满足 i < j 且 A_i > A_j,等价于使得 A 中有 x 对逆序对。

题目大意

求的是找出含 x 个逆序对的最小数组。

解题思路

首先考虑其中的特殊情况,如果构造的序列是单调递减的,那么这里逆序对数量就是 C_{n}^{2},其中 n 是序列长度,由于组合数是单调递增的,这样我们就可以通过 x 确定要构造的序列的长度。

那么就是在长度为 len 的数组中选一对逆序对的情况小于 x。

即 C_{len}^{2} < x。

解这个方程,负根舍去,得到 len \geq \frac{1+\sqrt{1+8x}}{2}。

那么 len = \lceil\frac{1+\sqrt{1+8x}}{2}\rceil。

接着,我们试着去构造一些合法的序列。

x = 21 a = [7 6 5 4 3 2 1]
x = 22 a = [2 6 5 4 3 2 1 1]
x = 23 a = [3 5 4 3 2 2 1 1]
x = 24 a = [4 4 3 3 2 2 1 1]
x = 25 a = [5 4 3 3 2 2 1 1]
x = 26 a = [6 5 4 3 2 2 1 1]
x = 27 a = [7 6 5 4 3 2 1 1]
x = 28 a = [8 7 6 5 4 3 2 1]

不难发现,当 x = C_{len}^{2} 时,我们可以直接去构造一个单调递减的序列。

当 C_{len}^{2}-x \leq \lfloor \frac{len}{2} \rfloor 的时候,这后面的 (C_{len}^{2}-x) \times 2 个是从 1 开始的单调递增的序列,这其中每两个是同一个数字,剩余前面的数字继续递增。剩余的情况里,后面 (x- C_{len-1}^{2}) \times 2 个是从 1 开始的递增序列,每两个是同一个数字,剩余除了第一个数字继续递增,但是这里第一个数字是比较特殊的,是 x-C_{len-1}^{2}+1。

#include <bits/stdc++.h>
using namespace std;
#define maxn 1000005
#define maxa 1005
#define repr(i,a,b) for(int i = a;i <= b;i++) 
#define int long long
vector<int> v;
int x,len;
signed main(){
    cin.tie(0)->ios::sync_with_stdio(false);
    cout.tie(0);
    cin>>x;
    int len = ceil((1+sqrt(1+8*x))/2);
    cout<<len<<endl;
    if(x==len*(len-1)/2){
        for(int i = len;i > 0;i--){
            cout<<i<<" ";
        }
        return 0;
    }
    else{
        int u = 1;
        if(len*(len-1)/2<=x+len/2){
            while(u<=len*(len-1)/2-x){
                v.push_back(u);
                v.push_back(u);
                u++;
            }
            while(v.size()<len){
                v.push_back(u++);
            }
        }
        else{
            while(u<=x-(len-1)*(len-2)/2){
                v.push_back(u);
                v.push_back(u);
                u++;
            }
            while(v.size()<len-1){
                v.push_back(u++);
            }
            v.push_back(x-(len-1)*(len-2)/2+1);
        }
    }
    reverse(v.begin(),v.end());
    for(auto ans:v){
        cout<<ans<<" ";
    }
    return 0;
}