-
Notifications
You must be signed in to change notification settings - Fork 0
/
minmum cost.cpp
40 lines (37 loc) · 1.15 KB
/
minmum cost.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
long long minimumCost(string source, string target, vector<char>& original, vector<char>& changed, vector<int>& cost) {
const int inf = 1 << 29;
int g[26][26];
for (int i = 0; i < 26; ++i) {
fill(begin(g[i]), end(g[i]), inf);
g[i][i] = 0;
}
for (int i = 0; i < original.size(); ++i) {
int x = original[i] - 'a';
int y = changed[i] - 'a';
int z = cost[i];
g[x][y] = min(g[x][y], z);
}
for (int k = 0; k < 26; ++k) {
for (int i = 0; i < 26; ++i) {
for (int j = 0; j < 26; ++j) {
g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
}
}
}
long long ans = 0;
int n = source.length();
for (int i = 0; i < n; ++i) {
int x = source[i] - 'a';
int y = target[i] - 'a';
if (x != y) {
if (g[x][y] >= inf) {
return -1;
}
ans += g[x][y];
}
}
return ans;
}
};