cf1768 E. Partial Sorting(数学 + 容斥原理)

传送门

#include <bits/stdc++.h>

using namespace std;

#define endl "\n"
#define debug cout<<"debug"<<endl
mt19937 rd(time(0));
typedef long long ll;
typedef long double ld;
typedef pair<int, int> PII;
const double eps = 1e-8;
const double PI = 3.14159265358979323;
const int N = 3e6+10, M = 2*N/*, mod = 998244353*/;
const int INF = 0x3f3f3f3f;

int n, mod;
ll fact[N], invfact[N];

ll qmi(ll a, ll k)
{
    ll res = 1;
    while(k)
    {
        if(k&1) res = res*a % mod;
        k>>=1;
        a = a*a % mod;
    }
    return res;
}

ll C(int a, int b) // 以a为底的组合数
{
    return fact[a]*invfact[b] % mod * invfact[a-b] % mod;
}

void solve()
{
    cin>>n>>mod;

    fact[0] = invfact[0] = 1;
    for(int i = 1; i<N; i++)
        fact[i] = fact[i-1]*i % mod;
    invfact[N-1] = qmi(fact[N-1], mod-2);
    for(int i = N-2; i>=1; i--)
        invfact[i] = invfact[i+1]*(i+1) % mod;

    // x = 0, 0次对答案无贡献
    ll res = 0;

    // x = 1, 前n个排序好/后n个排序好, 共2*(fact[2n]-1) - 同时满足的 即前n后n都排序好, 中间n的, 共fact[n]-1, 1表示x=0的状态
    ll num1 = ((2ll*(fact[2*n]-1)%mod - (fact[n]-1))%mod + mod) %mod;
    res = (res + num1) % mod;

    // x = 2, 前n个元素在1~2n/后n个在n+1~3n, 共2*(C{2n, n}*A{n, n}*A{2n, 2n})
    // 容斥减去都满足的, 即判断下前n个元素有 i个 在n+1~2n, 后n个元素有 n-i个 在n+1~2n,
    // 即 C{n, i}*C{n, n-i}*fact[n] * C(2*n-i, n)*fact[n] * fact[n]
    // 枚举下i即可
    ll num2 = 2ll*((C(2*n, n)*fact[n]%mod) * fact[2*n] % mod) % mod;
    for(int i = 0; i<=n; i++)
    {
        num2 = ((num2 - (C(n, i)*C(n, n-i) % mod * fact[n] %mod * C(2*n-i, n) % mod * fact[n] % mod * fact[n] % mod))%mod + mod)%mod;
    }
    num2 = (num2 - 1 - num1 + mod) % mod;
    res = (res + 2ll*num2 % mod) % mod;

    // x = 3, 用总的减去前三种即可
    ll num3 = (fact[3*n] - 1 - num1 - num2 + mod) % mod;
    res = (res + 3ll*num3 % mod) % mod;

    cout<<(res+mod)%mod<<endl;
}

int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    int T;
    T = 1;

//    cin>>T;
    while(T -- )
    {
        solve();
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值