2976.cpp (1146B)
1 class Solution { 2 public: 3 long long minimumCost(const string &source, const string &target, const vector<char> &original, 4 const vector<char> &changed, const vector<int> &cost) const { 5 static unsigned long long path[26][26]; 6 memset(path, 0xFF, sizeof(path)); 7 8 for (int i = 0; i < size(cost); i++) { 9 auto &cpath = path[original[i] - 'a'][changed[i] - 'a']; 10 cpath = min(cpath, (unsigned long long)cost[i]); 11 } 12 13 for (int k = 0; k < 26; k++) { 14 for (int i = 0; i < 26; i++) { 15 if (path[i][k] == -1) continue; 16 17 for (int j = 0; j < 26; j++) { 18 if (path[k][j] == -1) continue; 19 20 path[i][j] = min(path[i][j], path[i][k] + path[k][j]); 21 } 22 } 23 } 24 25 long long res = 0; 26 27 for (int i = 0; i < size(source); i++) { 28 if (source[i] == target[i]) continue; 29 30 const auto cost = path[source[i] - 'a'][target[i] - 'a']; 31 if (cost == -1) return -1; 32 33 res += cost; 34 } 35 36 return res; 37 } 38 };