设
f[r1][r2][r3][r4][r5][last]
为剩余
1
次使用机会的,剩余
那么记忆化搜索转移即可
注意 last 记录的上一次中剩余为 last 的,到本次中为 last−1 ,那么就要减去 (last==ai)
#include <cstdio>
using namespace std;
typedef long long LL;
const int SN = 17;
const int MOD = 1e9 + 7;
LL f[SN][SN][SN][SN][SN][6], n, x,rmn[SN];
void Read(LL &x) {
LL in = 0, f = 1; char ch = getchar();
while(ch<'0' || ch>'9') {if(ch=='-') f = -1; ch = getchar();}
while(ch>='0' && ch<='9') {in = in*10+ch-'0'; ch = getchar();}
x = in*f;
}
LL dfs(int r1,int r2,int r3,int r4,int r5,int last) {
if( (r1|r2|r3|r4|r5) == 0 ) return f[r1][r2][r3][r4][r5][last] = 1;
if(f[r1][r2][r3][r4][r5][last]) return f[r1][r2][r3][r4][r5][last];
LL now = 0;
if(r1) now = (now + (r1-(last==2))*dfs(r1-1,r2,r3,r4,r5,1))%MOD;
if(r2) now = (now + (r2-(last==3))*dfs(r1+1,r2-1,r3,r4,r5,2))%MOD;
if(r3) now = (now + (r3-(last==4))*dfs(r1,r2+1,r3-1,r4,r5,3))%MOD;
if(r4) now = (now + (r4-(last==5))*dfs(r1,r2,r3+1,r4-1,r5,4))%MOD;
if(r5) now = (now + r5*dfs(r1,r2,r3,r4+1,r5-1,5))%MOD;
return f[r1][r2][r3][r4][r5][last] = now;
}
int main() {
Read(n);
for(int i = 1; i <= n; i++) Read(x),rmn[x]++;
dfs(rmn[1],rmn[2],rmn[3],rmn[4],rmn[5],0);
printf("%lld\n",f[rmn[1]][rmn[2]][rmn[3]][rmn[4]][rmn[5]][0]);
return 0;
}