CF BUDDY
← Problems·

1906J · Count BFS Graph

2100 · combinatorics, dp

Problem: You are currently researching a graph traversal algorithm called the Breadth First Search (BFS). Suppose you have an input graph of NN nodes (numbered from 11 to NN). The graph is represented by an adjacency matrix MM, for which node uu can traverse to node vv if Mu,vM_{u, v} is 11, otherwise it is 00. Your algorithm will output the order the nodes are visited in the BFS. The pseudocode of the algorithm is presented as follows.

During your research, you are interested in the following problem. Given an array AA such that AA is a permutation of 11 to NN and A1=1A_1 = 1. How many simple undirected graph with NN nodes and adjacency matrix MM such that BFS(M)=A\text{BFS}(M) = A? Since the answer can be very large, calculate the answer modulo 998244353998\,244\,353.

A simple graph has no self-loop (Mi,i=0M_{i, i} = 0 for 1iN1 \leq i \leq N) and there is at most one edge that connects a pair of nodes. In an undirected graph, if node uu is adjacent to node vv, then node vv is also adjacent to node uu; formally, Mu,v=Mv,uM_{u, v} = M_{v, u} for 1u<vN1 \leq u < v \leq N.

Two graphs are considered different if there is an edge that exists in one graph but not the other. In other words, two graphs are considered different if their adjacency matrices are different.

Input Format: The first line consists of an integer NN (2N50002 \leq N \leq 5000).

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

Output Format: Output an integer representing the number of simple undirected graphs with NN nodes and adjacency matrix MM such that BFS(M)=A\text{BFS}(M) = A. Since the answer can be very large, output the answer modulo 998244353998\,244\,353.

Note: Explanation for the sample input/output #1

The following illustration shows all graphs that satisfy the requirements.

Explanation for the sample input/output #2

The only graph that satisfies the requirements is a graph with two edges: one that connects nodes 11 and 33, and another one that connects nodes 33 and 22.

Sample Cases

Case 1

Input

3
1 2 3

Output

3

Case 2

Input

3
1 3 2

Output

1

Case 3

Input

5
1 3 2 4 5

Output

17

Case 4

Input

11
1 2 3 4 5 6 7 8 9 10 11

Output

379394847

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback