101975: [AtCoder]ABC197 F - Construct a Palindrome

Memory Limit:256 MB Time Limit:2 S
Judge Style:Text Compare Creator:
Submit:0 Solved:0

Description

Score : $600$ points

Problem Statement

We have a connected undirected graph with $N$ vertices and $M$ edges, which is not necessarily simple.
Edge $i$ connects Vertex $A_i$ and Vertex $B_i$, and has a character $C_i$ written on it.
Let us make a string by choosing a path from Vertex $1$ to Vertex $N$ (possibly with repetitions of the same edge and vertex) and arrange the characters written on the edges in that path.
Determine whether this string can be a palindrome. If it can, find the minimum possible length of such a palindrome.

Constraints

  • $2 \le N \le 1000$
  • $1 \le M \le 1000$
  • $1 \le A_i \le N$
  • $1 \le B_i \le N$
  • $C_i$ is a lowercase English letter.
  • The given graph is connected.

Input

Input is given from Standard Input in the following format:

$N$ $M$
$A_1$ $B_1$ $C_1$
$A_2$ $B_2$ $C_2$
$A_3$ $B_3$ $C_3$
$\hspace{25pt} \vdots$
$A_M$ $B_M$ $C_M$

Output

If a palindrome can be made, print the minimum possible length of such a palindrome; otherwise, print -1.


Sample Input 1

8 8
1 2 a
2 3 b
1 3 c
3 4 b
4 5 a
5 6 c
6 7 b
7 8 a

Sample Output 1

10

By traversing the edges in the order $1, 2, 3, 1, 2, 4, 5, 6, 7, 8$, we can make a string abcabbacba, which is a palindrome.
It is impossible to make a shorter palindrome, so the answer is $10$.


Sample Input 2

4 5
1 1 a
1 2 a
2 3 a
3 4 b
4 4 a

Sample Output 2

5

By traversing the edges in the order $2, 3, 4, 5, 5$, we can make a string aabaa, which is a palindrome.
Note that repetitions of the same edge and vertex are allowed.


Sample Input 3

3 4
1 1 a
1 2 a
2 3 b
3 3 b

Sample Output 3

-1

We cannot make a palindrome.

Input

题意翻译

有一个 $N$ 个点,$M$ 条边的无向联通图(图可能不是简单的,意味着可能有环)。第 $i$ 条边连接着点 $A_i$ 和 $B_i$,上面有个英文小写字母 $C_i$。一条从点 $1$ 开始,点 $N$ 结束的回文路径满足:在路径上的边顺次取出字母(也就是取出 $C_i$),最后形成的字符串回文(注意:这并不是简单路径,可能会经过重复的点或边)。求从 $1$ 开始 $N$ 结束的最短回文路径长度。

加入题单

上一题 下一题 算法标签: