Under construction

Still being built. Things may change

Count BFS Graph

Time limit2sMemory limit1024 MB

Summary
Count the simple undirected graphs on N nodes whose BFS from node 1 visits the nodes in the given order A, modulo 998244353.
Level

Medium7 of 10

Topics
Graph, BFS, Dynamic programming, Combinatorics
Solved
No attempts yet

Problem

You are researching a graph traversal algorithm called Breadth First Search (BFS). Suppose you have a graph with NN nodes numbered from 11 to NN. The graph is given as an adjacency matrix MM, where node uu can traverse to node vv if Mu,vM_{u,v} is 11, and otherwise Mu,vM_{u,v} is 00. The algorithm outputs the order in which nodes are visited.

BFS(M[1..N][1..N]):
    let A be an empty array
    let Q be an empty queue

    append 1 to A
    push 1 to Q

    while Q is not empty:
        pop the front element of Q into u
        for v = 1 to N:
            if M[u][v] == 1 and v is not in A:
                append v to A
                push v to Q

    return A

Given an array AA that is a permutation of 11 to NN with A1=1A_1 = 1, count the simple undirected graphs with NN nodes whose adjacency matrix MM satisfies BFS(M)=A\text{BFS}(M) = A. Output the count modulo 998 244 353998\,244\,353.

A simple graph has no self-loops (Mi,i=0M_{i,i} = 0 for 1≤i≤N1 \le i \le N), and each pair of nodes is connected by at most one edge. In an undirected graph, Mu,v=Mv,uM_{u,v} = M_{v,u} for 1≤u<v≤N1 \le u < v \le N. Two graphs are different if their adjacency matrices differ.

Input

The first line contains an integer NN (2≤N≤50002 \le N \le 5000).

The second line contains NN integers AiA_i. The array AA is a permutation of 11 to NN, and A1=1A_1 = 1.

Output

Print the number of simple undirected graphs with NN nodes whose adjacency matrix MM satisfies BFS(M)=A\text{BFS}(M) = A, modulo 998 244 353998\,244\,353.

Examples4

  1. Example 1

    Input
    3
    1 2 3
    
    Expected output
    3
    
  2. Example 2

    Input
    3
    1 3 2
    
    Expected output
    1
    
  3. Example 3

    Input
    5
    1 3 2 4 5
    
    Expected output
    17
    
  4. Example 4

    Input
    11
    1 2 3 4 5 6 7 8 9 10 11
    
    Expected output
    379394847