题解:P8107 [Cnoi2021] 未来试题

· · 题解

OJ远古题,甚至加了点无关紧要的数据范围

题目分析

很大的直接算似乎很困难,考虑从小到大一个个加入数。

注意到加入一个数 a 时,a 大于任意当前数列中的数,那么其加入在数列的第 i 位时,就会产生 n-i 个逆序对(因为其后面的数都小于它)。

然后,由于是等概率生成的所有字符串,有其插入所有位置的概率都相同。

定义 f_{i,j} 表示当前插入 i 逆序对数模 k 为 j 的概率。

那么我们有

f_{i,j} = \frac{\sum\limits_{l=0}^{l-1} f_{i-1,(j+l \bmod k)}}{i}

直接转移是 O(nk^2) 的,空间复杂度也是 O(nk)。

发现每次取到贡献的都是一段连续区间。容易滚动数组加上前缀和优化到时间复杂度 O(nk),空间复杂度 O(n)。

足以通过此题。

代码

#include<bits/stdc++.h>
#define int long long
#define pb push_back
#define fi first
#define se second
#define PII pair<int,int>
namespace IO {
    #define gh getchar
    inline int read(){char ch=gh();int x=0;bool t=0;while(ch<'0'||ch>'9')   t|=ch=='-',ch=gh();while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=gh();return t?-x:x;}
    inline char getc(){char ch=gh();while(ch<'a'||ch>'z') ch=gh();return ch;}
    inline void write(int x){if(x < 0){putchar('-');x = -x;}if(x > 9){write(x / 10);}putchar((x % 10 + '0'));}
}
using namespace IO;
using namespace std;
#define Tp template<typename T>
#define Ts template<typename T,typename... Ar>
namespace Debug{
    Tp void _debug(char* f,T t){cerr<<f<<'='<<t<<endl;}
    Ts void _debug(char* f,T x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
    #ifdef LOCAL
    #define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__)
    #else                                               
    #define gdb(...) void()
    #endif
}using namespace Debug;
const int Maxn = 1e5 + 10, mod = 998244353;
int a[Maxn];
int qPow(int a, int b = mod - 2){
    int res = 1;
    while(b){
        if(b & 1) res = res * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return res;
}
int f[2][Maxn];
int s[Maxn];
int qry(int l, int r){
    if(l > r) return 0;
    if(l < 0) return 0;
    return s[r] - (l == 0 ? 0 : s[l - 1]);
}
signed main(){
    int n = read(), k = read();
    if(k <= n){
        int x = qPow(k, mod - 2);
        gdb(k, x);
        for(int i = 1; i <= k; i++) cout << x << ' ';
    }else {
        f[0][0] = 1;

        s[0] = f[0][0];
            for(int j = 1; j < k; j++) s[j] = s[j - 1] + f[0][j];
        for(int i = 1; i <= n; i++){
            gdb(i);
            for(int j = 0; j < k; j++){
                gdb(j);
                int sm = 0;
                //0 ~ (i - 1)
                int lft = j;
                int rgt = k - (i - lft) + 1;
                if(j > (i - 1)){
                    f[i%2][j] = qry(j - i + 1, j);
                    gdb(j-i+1,j, qry(j - i + 1, j));
                }else {
                    f[i%2][j] = qry(0, j) + qry(rgt,k-1);
                    gdb(lft,rgt);
                }
                f[i%2][j] %= mod;
                f[i%2][j] = f[i%2][j] * qPow(i) % mod;
            }
            s[0] = f[i % 2][0];
            for(int j = 1; j < k; j++) s[j] = s[j - 1] + f[i % 2][j];

        }
            for(int j = 0; j < k; j++)
                cout << f[n%2][j] << ' ';
    }
}