#P7323. [WC2021] 括号路径

[WC2021] 括号路径

Description

Given a directed graph with nn vertices and 2m2 m edges, each edge has a label, which is either a left bracket or a right bracket. There are kk different bracket types, so the graph may contain 2k2 k different labels. Vertices, edges, and bracket types are all numbered starting from 11.

Each edge in the graph appears in a paired way with another edge. More specifically, if there is an edge (u,v)(u, v) labeled with the left bracket of type ww, then there must be an edge (v,u)(v, u) labeled with the right bracket of the same type ww. Similarly, every edge labeled with a right bracket corresponds to an opposite-direction edge labeled with the left bracket of the same type.

Now you need to compute how many pairs of vertices (x,y)(x, y) (1x<yn1 \le x < y \le n) satisfy the following: there exists a path from xx to yy in the graph such that, if you concatenate the labels of the edges along the path in the order they are traversed, the resulting string is a valid bracket sequence.

Input Format

The first line contains three integers n,m,kn, m, k, representing the number of vertices, the number of edge pairs, and the number of bracket types.

The next mm lines each contain three integers u,v,wu, v, w, indicating: a directed edge from uu to vv labeled with the left bracket of type ww; and a directed edge from vv to uu labeled with the right bracket of type ww.

In the given graph, there may be multiple directed edges between any two different vertices, but there are no self-loops, i.e., uvu \ne v.

Output Format

Output a single integer in one line, the number of vertex pairs that satisfy the condition.

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

3

6 8 2
6 1 2
3 5 1
1 2 2
5 1 2
3 6 2
4 3 1
6 2 2
3 2 1

10

见附件中的 bracket/bracket3.in
见附件中的 bracket/bracket3.ans
见附件中的 bracket/bracket4.in
见附件中的 bracket/bracket4.ans

Hint

[Sample Explanation #1]

The valid vertex pairs and their corresponding paths are:

(1,2)(1, 2): 134121 \to 3 \to 4 \to 1 \to 2.
(1,4)(1, 4): 1341 \to 3 \to 4.
(2,4)(2, 4): 2142 \to 1 \to 4.

[Constraints]

For all test cases: 1n3×1051 \le n \le 3 \times {10}^5, 1m6×1051 \le m \le 6 \times {10}^5, 1k,u,vn1 \le k, u, v \le n, 1wk1 \le w \le k.

The specific limits for each test case are shown in the table below:

Test Case ID n=n = mm \le kk \le Special Restriction
141 \sim 4 44 55 22 None.
585 \sim 8 88 1010
9129 \sim 12 30003000 60006000 11
131613 \sim 16 n1n - 1 nn There is no cycle consisting only of edges labeled with left brackets.
172017 \sim 20 3×1053 \times {10}^5
212521 \sim 25 6×1056 \times {10}^5 None.

Translated by ChatGPT 5