-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
55 lines (52 loc) · 1.51 KB
/
Solution.cs
File metadata and controls
55 lines (52 loc) · 1.51 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Solution
{
public long MinimumCost(string source, string target, char[] original, char[] changed, int[] cost)
{
List<int[]>[] graph = new List<int[]>[26];
for (int i = 0; i < 26; i++)
{
graph[i] = [];
}
for (int i = 0; i < cost.Length; i++)
{
int u = original[i] - 'a', v = changed[i] - 'a', c = cost[i];
graph[u].Add([v, c]);
}
long[,] map = new long[26, 26];
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < 26; j++)
{
map[i, j] = long.MaxValue;
}
map[i, i] = 0;
}
// pre calc cost
for (int i = 0; i < 26; i++)
{
PriorityQueue<int, long> pq = new();
pq.Enqueue(i, 0);
while (pq.Count > 0)
{
int u = pq.Dequeue();
foreach (var next in graph[u])
{
int v = next[0], c = next[1];
long nC = map[i, u] + c;
if (nC < map[i, v])
{
map[i, v] = nC;
pq.Enqueue(v, nC);
}
}
}
}
long ans = 0;
for (int i = 0; i < source.Length; i++)
{
if (map[source[i] - 'a', target[i] - 'a'] == long.MaxValue) return -1;
ans += map[source[i] - 'a', target[i] - 'a'];
}
return ans;
}
}