题解 SP9097 【NOVICE65 - Derangements HARD】
NaCly_Fish · · 题解
【模板】容斥原理
设
考虑排列后不变的位置上的数为
(
这个式子用可重复排列的对比一下,很容易就能理解(
然后大力枚举子集计算即可,每次时间复杂度
(代码枚举的位置,所以总是跑满的)
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#define reg register
#define ll long long
using namespace std;
inline void read(int &x){
x = 0;
char c = getchar();
while(c<'0'||c>'9') c = getchar();
while(c>='0'&&c<='9'){
x = (x<<3)+(x<<1)+(c^48);
c = getchar();
}
}
ll fac[16];
int cnt[16],cur[16],a[16];
int main(){
fac[0] = fac[1] = 1;
for(int i=2;i<=15;++i) fac[i] = fac[i-1]*i;
int T,n,lim,siz;
ll ans,qwq;
read(T);
while(T--){
read(n);
lim = 1<<n;
memset(cnt,0,sizeof(cnt));
for(int i=1;i<=n;++i){
read(a[i]);
++cnt[a[i]];
}
ans = 0;
for(reg int i=0;i!=lim;++i){
memcpy(cur,cnt,n<<2);
siz = __builtin_popcount(i);
qwq = fac[n-siz];
for(reg int j=0;j!=n;++j) cur[a[j+1]] -= (i>>j)&1;
for(reg int j=0;j!=n;++j) qwq /= fac[cur[j]];
ans += (siz&1)?-qwq:qwq;
}
printf("%lld\n",ans);
}
return 0;
}