The graph is layered according to the shortest path, then this diagram needs to meet each point up one level with only one edge and no more upward edge.
We use Dp[u][i][j][k][l] dp[u][i][j][k][l] to represent the first U u node, the previous layer has I I i reading 1 1 Plug and J J of the degree of 2 2 plug, this layer has k K degrees 1 1 Plug and l l degrees 2 2 of the plug. Note that we don't even have to worry about how much the shortest circuit is. Let's talk about the transfer. The current point is connected to a point in the previous layer, the remaining degrees can be left, or it can be connected to this layer.
#include <cstdio> #include <cstring> #include <algorithm> using namespace std;
#define LL Long Long #define DP dp[c][j][k][x][y] const int p=1000000007;
int d[55],n;
LL dp[2][51][51][51][51];
void Upd (LL &x,ll y) {x+=y;
X%=p;
} int main () {scanf ("%d", &n);
for (int i=1;i<=n;i++) scanf ("%d", &d[i]);
Dp[0][d[1]==2][d[1]==3][d[2]==2][d[2]==3]=1; for (int i=2,c=0;i<n;i++,memset (dp[c],0,sizeof (dp[c))), c^=1) for (int. j=0;j<=i;j++) for (int k=0
; j+k<=i;k++) for (int x=0;j+k+x<=i;x++) for (int y=0;j+k+x+y<=i;y++)
if (DP) {if (!j&&!k) {if (x| |
Y) upd (DP[C][X][Y][0][0],DP);
Continue
} if (d[i+1]==2) { if (j) {upd (Dp[c^1][j-1][k][x+1][y],
DP*J);
if (x) upd (dp[c^1][j-1][k][x-1][y],dp*j*x);
if (y) upd (dp[c^1][j-1][k][x+1][y-1],dp*j*y); } if (k) {upd (dp[c^1] [J+1] [K-1] [X+1]
[Y],dp*k];
if (x) upd (dp[c^1][j+1][k-1][x-1][y],dp*k*x);
if (y) upd (dp[c^1][j+1][k-1][x+1][y-1],dp*k*y);
}} else {
if (j) {upd (dp[c^1][j-1][k][x][y+1],dp*j);
if (x) upd (dp[c^1][j-1][k][x][y],dp*j*x); if (y) upd (dp[c^1][j-1][k][x+2][y-1],dp*j*y);
if (x>=2) upd (dp[c^1][j-1][k][x-2][y],dp*j*x* (x-1)/2);
if (x&&y) upd (dp[c^1][j-1][k][x][y-1],dp*j*x*y);
if (y>=2) upd (dp[c^1][j-1][k][x+2][y-2],dp*j*y* (y-1)/2); } if (k) {upd (dp[c^1] [J+1] [K-1] [x]
[Y+1],dp*k];
if (x) upd (dp[c^1][j+1][k-1][x][y],dp*k*x);
if (y) upd (dp[c^1][j+1][k-1][x+2][y-1],dp*k*y);
if (x>=2) upd (dp[c^1][j+1][k-1][x-2][y],dp*k*x* (x-1)/2);
if (x&&y) upd (dp[c^1][j+1][k-1][x][y-1],dp*k*x*y);
if (y>=2) upd (dp[c^1][j+1][k-1][x+2][y-2],dp*k*y* (y-1)/2); }}} printf ("%i64d\n", dp[n&1][0][0][0][0]); }