Your friend Tóti is an aspiring musician. He has written n songs, each of which has a hype rating of either 1, 2, or 3. A higher hype rating means the song has more energy. Tóti is planning his first live performance and needs your help. He wants to know how many setlists he can make. A setlist consist of at least three songs, the first song must have hype rating 1, the last song must have hype rating 3, and all other songs must have hype rating 2. Tóti also wants to play the songs in the same order he wrote them.
Given the hype rating of each of Tóti’s songs in the order he wrote them, how many setlists can he make?
Input
The first line of input consists of an integer n (1≤n≤106), the number of songs Tóti has written. The second line consists of n integers, each in {1,2,3}, giving the hype ratings of the n songs in the order they were written.
Output
Output the number of setlists Tóti can make. Since this number can be large, print it modulo 109+7.
Sample Input 1
9
1 1 1 2 2 2 3 3 3
Sample Output 1
63
Sample Input 2
8
1 2 1 2 3 1 2 3
Sample Output 2
15
#include <bits/stdc++.h>
using namespace std;
const int M = 1e9 + 7;
const int N = 1e6+10;
int dp[4][N];
int a[N];
int n, i, j;
int main()
{
scanf("%d", &n);
memset(dp, 0, sizeof(dp));
for (i = 1; i <= n; i++) scanf("%d", &a[i]);
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= n; j++)
{
if (a[j] == 1)
{
if (i == 1)
dp[i][j] = (1 + dp[i][j - 1]) % M;
else
dp[i][j] = (dp[i][j - 1]) % M;
}
else if (a[j] == 2)
{
if (i == 2)
dp[i][j] = (dp[i - 1][j - 1] + dp[i][j - 1] * 2) % M;
else
dp[i][j] = (dp[i][j - 1]) % M;
}
else
{
if (i == 3)
dp[i][j] = (dp[i - 1][j - 1] + dp[i][j - 1]) % M;
else
dp[i][j] = (dp[i][j - 1]) % M;
}
}
}
printf("%d\n", dp[3][n]);
}