# 宝石装箱 容斥+dp

2020-05-23 09:52:09  阅读：6  来源： 互联网

##### 题目:
• 有n个宝石和n个箱子，每个箱子只能放一个宝石且第i个宝石不能放在a[i]箱子中，问合适的放法数量，mod 998244353;

##### 题解：

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 a[N], num[N], dp[N], fac[N];

int main()
{
fac[0] = 1;
scanf("%lld",&n);
for(int i = 1; i <= n; ++ i) {
scanf("%lld",&a[i]);
num[a[i]] ++;
}
for(int i = 1; i <= n; ++ i) 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 = n; 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;
}