Approach
This is likely a APSP (all pair shortest path) problem, and can be done with Floyd-Warshall algorithm. Originally I was using 4-loops to check if the dist matrix is converging, but actually the algorithm only need 3 loops with k,i,j.
I also spend some time to review the floyd warshell algorithm. This is true due to the DP property. the original cost can be formed into a matrix dist_0, and when we construct dist_1, we iterate thorugh k=1 meaning that we allow 1 to be in the shortest path. When doing k=2, we allow 2,1 to be in the shortest path since we combine the solution from dist_1, and is currently looking into solution 2.
After realizing the algorithm, this problem is simple. We build the adjacency matrix to track the min cost, and then sum up all the cost.
Code
class Solution {
public:
long long minimumCost(string source, string target, vector<char>& original, vector<char>& changed, vector<int>& cost) {
const int sz = 26;
int adj[sz][sz];
for(int i = 0 ; i < sz ; ++i)
for(int j = 0 ; j < sz ; ++j)
adj[i][j] = INT_MAX;
int n = source.size();
int m = cost.size();
for(int i = 0 ; i < m ; ++i) {
adj[original[i]-'a'][changed[i]-'a'] = min(adj[original[i]-'a'][changed[i]-'a'], cost[i]);
}
for(int i = 0 ; i < sz ; ++i) adj[i][i] = 0;
for(int k = 0 ; k < sz ; ++k) {
for(int i = 0 ; i < sz ; ++i) {
for(int j = 0 ; j < sz ; ++j) {
if(adj[i][k] == INT_MAX || adj[k][j] == INT_MAX) continue;
else if(adj[i][k] + adj[k][j] < adj[i][j]) {
adj[i][j] = adj[i][k] + adj[k][j];
}
}
}
}
long long totalCost = 0;
for(int i = 0 ; i < n ; ++i) {
int curCost = adj[source[i]-'a'][target[i]-'a'];
if(curCost == INT_MAX) return -1;
totalCost += curCost;
}
return totalCost;
}
void print(int adj[10][10], int sz) {
for(int i = 0 ; i < sz ; ++i) {
for(int j = 0 ; j < sz ; ++j) {
cout << adj[i][j] << ' ';
} cout << endl;
}
cout << "---" << endl;
}
};