题目:
- 有n个宝石和n个箱子,每个箱子只能放一个宝石且第i个宝石不能放在a[i]箱子中,问合适的放法数量,mod 998244353;
题解:
总数减去不合法排列的数量就是要的答案。 计算不合法排列数量时容易明白需要用到容斥的做法。得到公式: (res = n! - sum_{i = 1}^{n} (-1)^{i - 1} * f[i]) 其中f[i]是有i个箱子放宝石不合法的排列量。所以问题变为计算f[i];
num[i]表示有num[i]个宝石不能放在i号箱子。dp[i][j]表示前i个箱子中j个箱子不合法的数量。那么有 (f[i] = (n-i)! * dp[n][i]),问题变成计算dp。
dp的转移: (dp[i][j] = dp[i-1][j] + dp[i-1][j-1] * num[j])
最后用容斥的式子计算就可以了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#include<queue>
#include<vector>
#include<string>
#include<fstream>
using namespace std;
#define rep(i, a, n) for(int i = a; i <= n; ++ i);
#define per(i, a, n) for(int i = n; i >= a; -- i);
typedef long long ll;
const int N = 1e4 + 105;
const ll mod = 998244353;
const double Pi = acos(- 1.0);
const int INF = 0x3f3f3f3f;
const int G = 3, Gi = 332748118;
ll qpow(ll a, ll b) { ll res = 1; while(b){ if(b & 1) res = (res * a) % mod; a = (a * a) % mod; b >>= 1;} return res; }
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
//
ll n;
ll num[N], dp[N], fac[N];
int main()
{
fac[0] = 1;
scanf("%lld",&n);
for(int i = 1; i <= n; ++ i) {
ll x; scanf("%lld",&x);
num[x] ++;
fac[i] = 1ll * i * fac[i - 1] % mod;
}
dp[0] = 1;
for(int i = 1; i <= n; ++ i){
if(!num[i]) continue;
for(int j = i; j >= 1; -- j){
dp[j] = (dp[j] + dp[j - 1] * num[i] % mod) % mod;
}
}
ll res = fac[n];
for(int i = 1; i <= n; ++ i){
if(i & 1) res = (res - fac[n - i] * dp[i] % mod + mod) % mod;
else res = (res + fac[n - i] * dp[i] % mod) % mod;
}
printf("%lld", res);
return 0;
}