Problem J

Statement
Copy Copied
Description:
You are currently researching a graph traversal algorithm called the Breadth First Search (BFS). Suppose you have an input graph of $$$N$$$ nodes (numbered from $$$1$$$ to $$$N$$$). The graph is represented by an adjacency matrix $$$M$$$, for which node $$$u$$$ can traverse to node $$$v$$$ if $$$M_{u, v}$$$ is $$$1$$$, otherwise it is $$$0$$$. 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 $$$A$$$ such that $$$A$$$ is a permutation of $$$1$$$ to $$$N$$$ and $$$A_1 = 1$$$. How many simple undirected graph with $$$N$$$ nodes and adjacency matrix $$$M$$$ such that $$$\text{BFS}(M) = A$$$? Since the answer can be very large, calculate the answer modulo $$$998\,244\,353$$$.

A simple graph has no self-loop ($$$M_{i, i} = 0$$$ for $$$1 \leq i \leq N$$$) and there is at most one edge that connects a pair of nodes. In an undirected graph, if node $$$u$$$ is adjacent to node $$$v$$$, then node $$$v$$$ is also adjacent to node $$$u$$$; formally, $$$M_{u, v} = M_{v, u}$$$ for $$$1 \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 $$$N$$$ ($$$2 \leq N \leq 5000$$$).

The second line consists of $$$N$$$ integers $$$A_i$$$. The array $$$A$$$ is a permutation of $$$1$$$ to $$$N$$$ and $$$A_1 = 1$$$.

Output Format:
Output an integer representing the number of simple undirected graphs with $$$N$$$ nodes and adjacency matrix $$$M$$$ such that $$$\text{BFS}(M) = A$$$. Since the answer can be very large, output the answer modulo $$$998\,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 $$$1$$$ and $$$3$$$, and another one that connects nodes $$$3$$$ and $$$2$$$.

Submissions

IDLanguageExit CodeTimestampCodeStdoutStderrRetry
4858 cpp 0 2026-03-04T12:26:46.95017Z View View View Retry
4857 cpp 1 2026-03-04T09:57:20.674138Z View View View Retry
4856 cpp 1 2026-03-04T09:53:01.731114Z View View View Retry
4854 cpp 1 2026-03-04T09:36:41.53381Z View View View Retry
4853 cpp 1 2026-03-04T09:33:12.213619Z View View View Retry
4852 cpp 1 2026-03-04T09:22:38.387379Z View View View Retry

Evaluations

Eval IDRun IDProviderModelLangSuccessTimestampPromptResponseStdoutStderrRetry
1439 20260302-080116 gemini gemini-3-pro-preview go false 2026-03-02T08:52:03.230991Z View View View View Retry