#P15095. [ICPC 2025 LAC] Ananna

[ICPC 2025 LAC] Ananna

题目描述

Dananland is a very typical country: it consists of NN cities, each identified by a distinct number. These cities are connected by MM unidirectional roads, where each road has a name.

Ananna is a bright little girl who lives in Dananland. Unfortunately, she was born with a terrible disease: she can only read backwards. After being a victim of terrible bullying by her peers, or, as Ananna calls them, sreep, she found solace in palindromes: words that are the same when read backwards.

Ananna’s mom, Evee, is trying to help her with her condition. One way she helps is by taking her on road trips. A road trip is a sequence of roads that starts at some city UU and ends at a different city VV; the same road may appear more than once.

While on a road trip, Evee asks Ananna the first letter of each road name, so she can practice looking at the start of words. This is, obviously, a source of great anxiety to Ananna, so to avoid having a kcatta cinap, Evee always makes sure that the sequence formed by taking the first letter of each road’s name, in the order they are traversed, is a palindrome.

Evee is now looking at a map of Dananland, and she wonders: How many distinct pairs of cities U,VU,V exist such that Evee can take a road trip from UU to VV?

输入格式

The first line contains two integers NN and MM (1N,M50001 \le N, M \le 5000), indicating respectively the number of cities and the number of roads in Dananland. Each city is identified by a distinct integer from 11 to NN.

Each of the next MM lines contains two integers UU and VV (1U,VN1 \le U, V \le N) and a lowercase letter CC, representing that there is a unidirectional road from UU to VV whose name starts with CC. Several roads may connect the same pair of cities, and a road may connect a city to itself.

输出格式

Output a single line with an integer indicating the number of pairs of cities U,VU,V such that UVU \ne V, there is a road trip from UU to VV, and the letters of the roads (in the order they are traversed) form a palindrome.

4 6
1 2 b
2 3 a
3 4 a
1 1 a
4 3 d
4 3 c
7
2 3
1 1 x
2 2 y
1 1 z
0

提示

Explanation of sample 1:

The 7 pairs of cities and possible road trips are:

  • 1,21,2: 1b21 \xrightarrow{b} 2
  • 1,31,3: $1 \xrightarrow{a} 1 \xrightarrow{b} 2 \xrightarrow{a} 3$
  • 1,41,4: $1 \xrightarrow{a} 1 \xrightarrow{a} 1 \xrightarrow{b} 2 \xrightarrow{a} 3 \xrightarrow{a} 4$
  • 2,32,3: 2a32 \xrightarrow{a} 3
  • 2,42,4: 2a3a42 \xrightarrow{a} 3 \xrightarrow{a} 4
  • 3,43,4: 3a43 \xrightarrow{a} 4
  • 4,34,3: 4d34 \xrightarrow{d} 3