G - Traveling Door-to-Door Salesman (Stairs) Editorial by evima
Let the rows where doors exist, in increasing order, be \(A'_1, \cdots, A'_{|A'|}\), and let the column numbers of doors in row \(A'_i\), in increasing order, be \(B'_{i,\ 1}, \cdots, B'_{i,\ |B'_i|}\).
By treating each cell as a vertex and interpreting movements between cells as the act of adding edges, this problem can be rephrased as finding the minimum total distance of an Eulerian path that passes through all \(N\) cells with doors and cell \((1,1)\).
Define a DP table \(dp_i[s][t][c]\) representing the state from row \(1\) through row \(A'_i\), with the following indices:
- \(s\) represents whether the degree of cell \((A'_i,\ 1)\) is \(0\), a positive odd number, or a positive even number.
- \(t\) represents whether the degree of cell \((A'_i,\ W)\) is \(0\), a positive odd number, or a positive even number.
- \(c\) represents whether cells \((A'_1,\ 1)\) and \((A'_1,\ W)\) both have positive degree and are disconnected from each other.
The transition from \(dp_{i-1}\) to \(dp_i\) can be written by brute-forcing over the following:
- The number of edges between cells \((A'_{i-1},\ 1)\) and \((A'_{i},\ 1)\) is \(0\), \(1\), or \(2\).
- The number of edges between cells \((A'_{i-1},\ W)\) and \((A'_{i},\ W)\) is \(0\), \(1\), or \(2\).
- Which of the following describes how edges are added within row \(A'_i\) (denoting cell \((A'_i,\ j)\) by column number \(j\)):
- Add one edge each from cell \(1\) to cell \(W\).
- Add two edges each from cell \(1\) to cell \(B'_{|B'_i|}\).
- Add two edges each from cell \(B'_{1}\) to cell \(W\).
- Add two edges each from cell \(1\) to cell \(B'_{j+0}\), and from cell \(B'_{j+1}\) to cell \(W\).
By writing the transitions so that no contradiction arises in the parity and sign of the degree at each vertex, and in connectivity, \(\displaystyle \min_{(s,t) \neq (0,0)} dp_{|A'|}[s][t][\mathrm{connected}]\) is the answer.
Implementation example (C++, 112 ms)
Proposed by: sheyasutaka
posted:
last update: