/
Time Limit: 2 sec / Memory Limit: 1024 MiB
配点 : 600 点
問題文
N 頂点 2N 辺の有向グラフが与えられます。頂点には 1 から N までの番号が付けられています。各頂点 i からは、文字 a が書かれた頂点 A_i への辺と、文字 b が書かれた頂点 B_i への辺がそれぞれ 1 本伸びています。
a, b のみからなる文字列 S を考えます。頂点 1 から出発し、S の各文字について先頭から順に、その文字が書かれた辺に沿って移動します。
このとき、すべての 辺 を少なくとも 1 回通るような文字列 S の長さの最小値を求めてください。ただし、そのような文字列が存在しない場合は -1 を出力してください。
T 個のテストケースが与えられるので、それぞれについて答えを求めてください。
制約
- 1 \le T \le 2000
- 1 \le N \le 2000
- すべてのテストケースにおける N の総和は 2000 以下
- 1 \le A_i,B_i \le N
- 入力は全て整数
入力
入力は以下の形式で標準入力から与えられる。
T
\mathrm{case}_1
\vdots
\mathrm{case}_T
各テストケースは以下の形式で与えられる。
N A_1 B_1 \vdots A_N B_N
出力
各テストケースに対する答えを順に改行区切りで出力せよ。
入力例 1
3 2 2 1 1 2 3 2 3 2 2 3 3 2 2 1 1 1
出力例 1
4 -1 5
1 つ目のテストケースでは S= baba とすると、 1 \to 1 \to 2 \to 2 \to 1 と移動します。このとき、存在する 4 本の辺を 1 回ずつ通ることができます。よって 4 と出力してください。
2 つ目のテストケースでは、頂点 1 を 2 回訪れることはできないため、すべての辺を通ることはできません。よって -1 と出力してください。また、辺に書かれた文字が異なるような多重辺が存在しうることに注意してください。
Score : 600 points
Problem Statement
You are given a directed graph with N vertices and 2N edges. The vertices are numbered 1 to N. From each vertex i, there is one edge labeled with the character a going to vertex A_i, and one edge labeled with the character b going to vertex B_i.
Consider a string S consisting only of a and b. Starting at vertex 1, for each character of S from the beginning, move along the edge labeled with that character.
Find the minimum length of a string S such that every edge is traversed at least once. If no such string exists, print -1.
You are given T test cases; solve each of them.
Constraints
- 1 \le T \le 2000
- 1 \le N \le 2000
- The sum of N over all test cases is at most 2000.
- 1 \le A_i,B_i \le N
- All input values are integers.
Input
The input is given from Standard Input in the following format:
T
\mathrm{case}_1
\vdots
\mathrm{case}_T
Each test case is given in the following format:
N A_1 B_1 \vdots A_N B_N
Output
Print the answers for the test cases in order, separated by newlines.
Sample Input 1
3 2 2 1 1 2 3 2 3 2 2 3 3 2 2 1 1 1
Sample Output 1
4 -1 5
In the first test case, if S= baba, you move as 1 \to 1 \to 2 \to 2 \to 1. This traverses each of the 4 edges exactly once. Thus, print 4.
In the second test case, vertex 1 cannot be visited twice, so it is impossible to traverse all the edges. Thus, print -1. Also, note that there may be multi-edges with different labels.