luogu#P4790. [BalticOI 2018] 多角恋

    ID: 3813 远端评测题 2000ms 750MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>动态规划 DP贪心2018深度优先搜索 DFSBalticOI(波罗的海)

[BalticOI 2018] 多角恋

Problem Description

This problem is translated from BalticOI 2018 Day 1 “Love Polygon”.

You are given a directed graph with NN vertices, where each vertex has out-degree 11. Each time, you may pay a cost of 11 to change the destination of one edge in the graph, i.e., change which vertex is reached from a given starting vertex. Find the minimum total cost needed to make the graph become several pairwise disjoint 2-cycles, and every vertex in the graph must belong to some cycle.

Input Format

The first line contains an integer NN.

The next NN lines each contain two strings ss and tt, meaning there is an edge sts\rightarrow t in the graph.

Each string contains only lowercase English letters and has length at most 1010.

Output Format

Output one integer, the minimum total cost needed to make the graph become several pairwise disjoint 2-cycles, and every vertex in the graph must belong to some cycle. If there is no solution, output 1-1.

8
leonard emmy
ada emmy
isaac leonard
emmy pierre
pierre bernhard
bernhard emmy
sofia karl
karl sofia
3

4
a c
b c
c d
d d
3

3
rocky scarlet
scarlet patrick
patrick rocky
-1

Hint

Explanation for Sample 1

The only optimal solution is shown in the figure above. The upper part is the original graph, and the three vertices with a pink background are the starting vertices of the edges that need to be modified. The lower part shows the graph after the modifications.

Explanation for Sample 2

There are multiple optimal solutions. One of them is to change the edges starting from a, b, and d, so that they connect to b, a, and c, respectively.

Explanation for Sample 3

There are 33 vertices in the graph. No matter how you change the destinations of edges, there will always be one person not in any cycle.

Subtask Score Constraints Additional Limit
11 2121 2N202\leqslant N\leqslant 20 .
22 2525 2N1000002\leqslant N\leqslant 100\, 000 Each vertex has one incoming edge (self-loops may exist).
33 2929 There is no cycle consisting of two or more vertices.
44 2525 .

Translated by ChatGPT 5