CF BUDDY
← Problems·

1866C · Completely Searching for Inversions

1900 · dfs and similar, dp, graphs

Problem: Pak Chanek has a directed acyclic graph (a directed graph that does not have any cycles) containing NN vertices. Vertex ii has SiS_i edges directed away from that vertex. The jj-th edge of vertex ii that is directed away from it, is directed towards vertex Li,jL_{i,j} and has an integer Wi,jW_{i,j} (0Wi,j10\leq W_{i,j}\leq1). Another information about the graph is that the graph is shaped in such a way such that each vertex can be reached from vertex 11 via zero or more directed edges.

Pak Chanek has an array ZZ that is initially empty.

Pak Chanek defines the function dfs as follows:

Note that the function does not keep track of which vertices have been visited, so each vertex can be processed more than once.

Let's say Pak Chanek does dfs(1) once. After that, Pak Chanek will get an array ZZ containing some elements 00 or 11. Define an inversion in array ZZ as a pair of indices (x,y)(x, y) (x<yx < y) such that Zx>ZyZ_x > Z_y. How many different inversions in ZZ are there if Pak Chanek does dfs(1) once? Since the answer can be very big, output the answer modulo 998244353998\,244\,353.

Input Format: The first line contains a single integer NN (2N1052 \leq N \leq 10^5) — the number of vertices in the graph. The following lines contain the description of each vertex from vertex 11 to vertex NN.

The first line of each vertex ii contains a single integer SiS_i (0SiN10 \leq S_i \leq N-1) — the number of edges directed away from vertex ii.

The jj-th of the next SiS_i lines of each vertex ii contains two integers Li,jL_{i,j} and Wi,jW_{i,j} (1Li,jN1 \leq L_{i,j} \leq N; 0Wi,j10 \leq W_{i,j} \leq 1) — an edge directed away from vertex ii that is directed towards vertex Li,jL_{i,j} and has an integer Wi,jW_{i,j}. For each ii, the values of Li,1L_{i,1}, Li,2L_{i,2}, ..., Li,SiL_{i,S_i} are pairwise distinct.

It is guaranteed that the sum of SiS_i over all vertices does not exceed 21052 \cdot 10^5. There are no cycles in the graph. Each vertex can be reached from vertex 11 via zero or more directed edges.

Output Format: An integer representing the number of inversions in ZZ if Pak Chanek does dfs(1) once. Since the answer can be very big, output the answer modulo 998244353998\,244\,353.

Note: The following is the dfs(1) process on the graph.

In the end, Z=[0,1,0,1,1,0]Z=[0,1,0,1,1,0]. All of its inversions are (2,3)(2,3), (2,6)(2,6), (4,6)(4,6), and (5,6)(5,6).

Sample Cases

Case 1

Input

5
2
4 0
3 1
0
1
2 0
2
3 1
5 1
0

Output

4

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