- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 72 lines of C++ from the credited upstream file 2977.cpp.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- 9 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long minimumCost(string source, string target, vector<string>& original,4 vector<string>& changed, vector<int>& cost) {5 const unordered_set<int> subLengths = getSubLengths(original);6 const unordered_map<string, int> subToId = getSubToId(original, changed);7 const int subCount = subToId.size();8 9 10 vector<vector<long>> dist(subCount, vector<long>(subCount, LONG_MAX));11 12 13 vector<long> dp(source.length() + 1, LONG_MAX);14 15 for (int i = 0; i < cost.size(); ++i) {16 const int u = subToId.at(original[i]);17 const int v = subToId.at(changed[i]);18 dist[u][v] = min(dist[u][v], static_cast<long>(cost[i]));19 }20 21 for (int k = 0; k < subCount; ++k)22 for (int i = 0; i < subCount; ++i)23 if (dist[i][k] < LONG_MAX)24 for (int j = 0; j < subCount; ++j)25 if (dist[k][j] < LONG_MAX)26 dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);27 28 dp[0] = 0;29 30 for (int i = 0; i < source.length(); ++i) {31 if (dp[i] == LONG_MAX)32 continue;33 if (target[i] == source[i])34 dp[i + 1] = min(dp[i + 1], dp[i]);35 for (const int subLength : subLengths) {36 if (i + subLength > source.length())37 continue;38 const string subSource = source.substr(i, subLength);39 const string subTarget = target.substr(i, subLength);40 if (!subToId.contains(subSource) || !subToId.contains(subTarget))41 continue;42 const int u = subToId.at(subSource);43 const int v = subToId.at(subTarget);44 if (dist[u][v] < LONG_MAX)45 dp[i + subLength] = min(dp[i + subLength], dp[i] + dist[u][v]);46 }47 }48 49 return dp[source.length()] == LONG_MAX ? -1 : dp[source.length()];50 }51 52 private:53 unordered_map<string, int> getSubToId(const vector<string>& original,54 const vector<string>& changed) {55 unordered_map<string, int> subToId;56 for (const string& s : original)57 if (!subToId.contains(s))58 subToId[s] = subToId.size();59 for (const string& s : changed)60 if (!subToId.contains(s))61 subToId[s] = subToId.size();62 return subToId;63 }64 65 unordered_set<int> getSubLengths(const vector<string>& original) {66 unordered_set<int> subLengths;67 for (const string& s : original)68 subLengths.insert(s.length());69 return subLengths;70 }71};72