E - Magical Ornament Editorial by en_translator
Let us regard it as a graph, where the magical gems are vertices and the pairs of them that can be adjacent are edges.
Notice that the constraints of \(K\) is fairly small (\(K ≤ 17\)).
It can see that this problem is equivalent to the shortest Hamiltonian problem for vertices \(C_1, C_2, \dots,\) and \(C_K\).
Now let us consider solving this problem efficiently with Dynamic Programming (DP).
Let \(C\) be a set \(C = \{C_1, C_2, \dots, C_K\}\), \(S\) be a subset of \(C\), and \(i\) be an element of \(S\); define
\(dp[S][i] = {}\)(Minimum length of path that contains \(S\) and ends at \(i\))
then the answer for the problem is \(\displaystyle \min_{i}\{dp[C][i]\} + 1\).
This DP satisfies the following recurrence relations:
\(\displaystyle dp[\{i\}][i] = 0\)
\(\displaystyle dp[S][i] = \min_{j}\{dp[S \setminus \{i\}][j] + \text{dist}(i, j)\}\)
where \(\text{dist}(i, j)\) denotes the distance between vertices \(i, j\), so this dp can be calculated from smaller subsets to bigger (as long as \(\text{dist}(i, j)\) is known).
As for \(\text{dist}(i, j)\), since \(i, j \in C\), they can be calculated with \(K\) times of BFS, beginning with each of \(C_1, C_2, \dots,\) and \(C_K\).
Therefore, the problem can be solved in a total of \(O(2^KK^2+K(N+M))\) time.
Sample Code (C++) : https://atcoder.jp/contests/abc190/submissions/19761405
Sample Code (Python) : https://atcoder.jp/contests/abc190/submissions/19825273
posted:
last update: