Result: Accepted
Time: 8ms
Memory: 1716kB
#include<iostream>
#include<cstdio>
using namespace std;
const long long mod = 1000000007;
int a, b;
long long num[5], ans = 0;
char ch[22];
void dfs(long long x, long long y, long long z, int all, int last, long long sum){
if(x == num[1]&&y == num[2]&&z == num[3]){
ans = (ans + sum) % mod;
return;
}
if(all){
if(ch[all - 1] == '1'){
if(last == 1){
if(z < num[3]){
dfs(x, y, z + 1, all + 1, 3, sum * (num[3] - z) % mod);
}
}
else if(last == 3){
if(x < num[1]){
dfs(x + 1, y, z, all + 1, 1, sum * (num[1] - x) % mod);
}
}
}
else{
if(last == 1){
if(x < num[1]){
dfs(x + 1, y, z, all + 1, 1, sum * (num[1] - x) % mod);
}
if(y < num[2]){
dfs(x, y + 1, z, all + 1, 2, sum * (num[2] - y) % mod);
}
}
else if(last == 2){
if(x < num[1]){
dfs(x + 1, y, z, all + 1, 1, sum * (num[1] - x) % mod);
}
if(y < num[2]){
dfs(x, y + 1, z, all + 1, 2, sum * (num[2] - y) % mod);
}
if(z < num[3]){
dfs(x, y, z + 1, all + 1, 3, sum * (num[3] - z) % mod);
}
}
else if(last == 3){
if(y < num[2]){
dfs(x, y + 1, z, all + 1, 2, sum * (num[2] - y) % mod);
}
if(z < num[3]){
dfs(x, y, z + 1, all + 1, 3, sum * (num[3] - z) % mod);
}
}
}
}
else{
if(num[1]){
dfs(1, 0, 0, 1, 1, num[1]);
}
if(num[2]){
dfs(0, 1, 0, 1, 2, num[2]);
}
if(num[3]){
dfs(0, 0, 1, 1, 3, num[3]);
}
}
}
int main(void){
int i;
scanf("%d",&a);
num[1] = num[2] = num[3] = 0;
while(a--){
scanf("%d",&b);
num[b]++;
}
scanf("%s",ch);
dfs(0, 0, 0, 0, -1 ,0);
printf("%lld\n",ans);
return 0;
}