../ Competitive Programming
-rw-r--r--aguang1.8 KiB2 min read

Leet Code Daily 2024-04-27 - Freedom Trail

Solution

First, let's say:

  • M=len(ring)M = len(\text{ring})
  • N=len(key)N = len(\text{key})

DP

If we define:

  • F(i,j)=minimum steps to rotate from ringi to ringjF(i, j) = \text{minimum steps to rotate from } \text{ring}_i \text{ to } \text{ring}_j
  • G(i,j)=minimum steps to spell key0..i if keyi is spelled by ringjG(i, j) = \text{minimum steps to spell } \text{key}_{0..i} \text{ if } \text{key}_i \text{ is spelled by } \text{ring}_j

Obviously,

F(i,j)=min⁡(∣i−j∣,M−∣i−j∣)F(i, j) = \min(\lvert i - j \rvert, M- \lvert i - j \rvert) G(i,j)={+∞if keyi≠ringj1+F(0,j)if keyi=ringj∧i=01+min⁡0≤k<MF(j,k)+G(i−1,k)if keyi=ringj∧i>0G(i, j)= \begin{cases} +\infty & \text{if } key_i \ne ring_j \\ 1 + F(0, j) & \text{if } key_i = ring_j \land i = 0 \\ 1 + \min_{0 \leq k \lt M}{ F(j, k) + G(i - 1, k) } & \text{if } key_i = ring_j \land i > 0 \end{cases}

And the answer should be min⁡0≤i<MF(N−1,i)\min_{0 \leq i \lt M}F(N - 1, i).

Code

c++
constexpr int kMaxSteps = 100 * 101;

class Solution {
public:
    int findRotateSteps(string ring, string key) {
        const int m = ring.size(), n = key.size();
        auto f = [&](int i, int j) {
            const int d = std::abs(i - j);
            return std::min(d, m - d);
        };
        int g[100][100];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                g[i][j] = kMaxSteps;
                if (key[i] != ring[j]) {
                    continue;
                }
                if (i == 0) {
                    g[i][j] = 1 + f(0, j);
                } else {
                    for (int k = 0; k < m; k++) {
                        g[i][j] = std::min(g[i][j], 1 + f(j, k) + g[i - 1][k]);
                    }
                }
            }
        }
        int ans = kMaxSteps;
        for (int i = 0; i < m; i++) {
            ans = std::min(ans, g[n - 1][i]);
        }
        return ans;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window