E - Palindromic Shortest Path Editorial by kkk_redbag_1314

O(n^3+26n^2) solution

In the official solution, enumerating outgoing/incoming edges for pairs of nodes leads to a transition time complexity of \(O(n^2)\).

However, we can optimize this via stepwise transitions. Specifically:

  • Let \(f_{x,y}\) denote the shortest palindromic path from node \(x\) to node \(y\).
  • Let \(g_{x,y,\text{col}}\) denote the shortest path from \(x\) to \(y\) where:
    • The first edge has color \(\text{col}\),
    • The remaining edges form a palindromic sequence.

Transition Steps

  • \(f_{x,y}\): For all \(C_{z,x}\neq\) -, propagate \(f_{x,y}+1\) to \(g_{z,y,C_{z,x}}\). Time per transition is \(O(n)\), so the total time complexity is \(O(n^3)\).
  • \(g_{x,y,\text{col}}\): For all \(C_{y,z}=\text{col}\), propagate \(g_{x,y,\text{col}}+1\) to \(f_{x,z}\). For each node \(y\), track outgoing edges grouped by color, so that for every node \(y\), the time complexity is \(O(26n)\). Then the total time comlexity is \(O(26n^2)\).

Since all edge weights are \(1\), a BFS-based approach remains valid. Thus the problem can be solved with time comlexity \(O(n^3+26n^2)\).

Submission.

posted:
last update: