<p>You are given two <strong>0-indexed</strong> strings <code>source</code> and <code>target</code>, both of length <code>n</code> and consisting of <strong>lowercase</strong> English letters. You are also given two <strong>0-indexed</strong> character arrays <code>original</code> and <code>changed</code>, and an integer array <code>cost</code>, where <code>cost[i]</code> represents the cost of changing the character <code>original[i]</code> to the character <code>changed[i]</code>.</p>

<p>You start with the string <code>source</code>. In one operation, you can pick a character <code>x</code> from the string and change it to the character <code>y</code> at a cost of <code>z</code> <strong>if</strong> there exists <strong>any</strong> index <code>j</code> such that <code>cost[j] == z</code>, <code>original[j] == x</code>, and <code>changed[j] == y</code>.</p>

<p>Return <em>the <strong>minimum</strong> cost to convert the string </em><code>source</code><em> to the string </em><code>target</code><em> using <strong>any</strong> number of operations. If it is impossible to convert</em> <code>source</code> <em>to</em> <code>target</code>, <em>return</em> <code>-1</code>.</p>

<p><strong>Note</strong> that there may exist indices <code>i</code>, <code>j</code> such that <code>original[j] == original[i]</code> and <code>changed[j] == changed[i]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;acbe&quot;, original = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;e&quot;,&quot;d&quot;], changed = [&quot;b&quot;,&quot;c&quot;,&quot;b&quot;,&quot;e&quot;,&quot;b&quot;,&quot;e&quot;], cost = [2,5,5,1,2,20]
<strong>Output:</strong> 28
<strong>Explanation:</strong> To convert the string &quot;abcd&quot; to string &quot;acbe&quot;:
- Change value at index 1 from &#39;b&#39; to &#39;c&#39; at a cost of 5.
- Change value at index 2 from &#39;c&#39; to &#39;e&#39; at a cost of 1.
- Change value at index 2 from &#39;e&#39; to &#39;b&#39; at a cost of 2.
- Change value at index 3 from &#39;d&#39; to &#39;e&#39; at a cost of 20.
The total cost incurred is 5 + 1 + 2 + 20 = 28.
It can be shown that this is the minimum possible cost.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> source = &quot;aaaa&quot;, target = &quot;bbbb&quot;, original = [&quot;a&quot;,&quot;c&quot;], changed = [&quot;c&quot;,&quot;b&quot;], cost = [1,2]
<strong>Output:</strong> 12
<strong>Explanation:</strong> To change the character &#39;a&#39; to &#39;b&#39; change the character &#39;a&#39; to &#39;c&#39; at a cost of 1, followed by changing the character &#39;c&#39; to &#39;b&#39; at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of &#39;a&#39; to &#39;b&#39;, a total cost of 3 * 4 = 12 is incurred.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> source = &quot;abcd&quot;, target = &quot;abce&quot;, original = [&quot;a&quot;], changed = [&quot;e&quot;], cost = [10000]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It is impossible to convert source to target because the value at index 3 cannot be changed from &#39;d&#39; to &#39;e&#39;.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= source.length == target.length &lt;= 10<sup>5</sup></code></li>
	<li><code>source</code>, <code>target</code> consist of lowercase English letters.</li>
	<li><code>1 &lt;= cost.length == original.length == changed.length &lt;= 2000</code></li>
	<li><code>original[i]</code>, <code>changed[i]</code> are lowercase English letters.</li>
	<li><code>1 &lt;= cost[i] &lt;= 10<sup>6</sup></code></li>
	<li><code>original[i] != changed[i]</code></li>
</ul>

class Solution:
    def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int:
        def dijkstra(g, c, start):
            pq = []  # Priority queue for Dijkstra's algorithm
            visited = set()  # Set to keep track of visited nodes
            heappush(pq, (0, start))  # Push the start node with 0 cost
            dist = {key: float('inf') for key in ascii_lowercase}  # Initialize distances to infinity
            dist[start] = 0  # Distance to start node is 0
            
            while pq:
                cur_cost, cur_node = heappop(pq)  # Pop the node with the smallest distance
                if cur_node in visited:  # Skip if the node has already been visited
                    continue
                visited.add(cur_node)  # Mark the node as visited
                
                # Iterate over the neighbors of the current node
                for nxt in g[cur_node]:
                    # Update the distance if a shorter path is found
                    if nxt not in visited and dist[nxt] > cur_cost + c[ord(cur_node) - ord('a')][ord(nxt) - ord('a')]:
                        dist[nxt] = cur_cost + c[ord(cur_node) - ord('a')][ord(nxt) - ord('a')]
                        heappush(pq, (dist[nxt], nxt))  # Push the updated distance into the priority queue
            return dist

        # Initialize the graph and cost matrix
        g = {key: [] for key in ascii_lowercase}
        c = [[float('inf')] * 26 for _ in range(26)]
        for i in range(len(original)):
            g[original[i]].append(changed[i])  # Add the edge to the graph
            c[ord(original[i]) - ord('a')][ord(changed[i]) - ord('a')] = min(c[ord(original[i]) - ord('a')][ord(changed[i]) - ord('a')] ,cost[i])  # Update the cost matrix
        for i in range(26):
            c[i][i] = 0
        
        ans = 0  # Initialize the answer
        dists = {key: dijkstra(g, c, key) for key in ascii_lowercase}

        for start, end in zip(source, target):
            if start != end:
                # dis = dijkstra(g, c, start)  # Get the shortest distances from the start node
                if dists[start][end] == float('inf'):  # If the end node is not reachable
                    return -1
                else:
                    ans += dists[start][end]  # Add the distance to the answer
        return ans


        

        
# class Solution:
#     def minimumCost(
#         self,
#         source: str,
#         target: str,
#         original: List[str],
#         changed: List[str],
#         cost: List[int],
#     ) -> int:
#         # Create a graph representation of character conversions
#         adjacency_list = [[] for _ in range(26)]

#         # Populate the adjacency list with character conversions
#         conversion_count = len(original)
#         for i in range(conversion_count):
#             adjacency_list[ord(original[i]) - ord("a")].append(
#                 (ord(changed[i]) - ord("a"), cost[i])
#             )

#         # Calculate shortest paths for all possible character conversions
#         min_conversion_costs = [
#             self._dijkstra(i, adjacency_list) for i in range(26)
#         ]
#         for i in range(26):
#             print(min_conversion_costs[i])
        

#         # Calculate the total cost of converting source to target
#         total_cost = 0
#         for s, t in zip(source, target):
#             if s != t:
#                 char_conversion_cost = min_conversion_costs[ord(s) - ord("a")][
#                     ord(t) - ord("a")
#                 ]
#                 if char_conversion_cost == float("inf"):
#                     return -1  # Conversion not possible
#                 total_cost += char_conversion_cost

#         return total_cost

#     def _dijkstra(
#         self, start_char: int, adjacency_list: List[List[tuple]]
#     ) -> List[int]:
#         # Priority queue to store characters with their conversion cost, sorted by cost
#         priority_queue = [(0, start_char)]

#         # List to store the minimum conversion cost to each character
#         min_costs = [float("inf")] * 26

#         while priority_queue:
#             current_cost, current_char = heapq.heappop(priority_queue)

#             if min_costs[current_char] != float("inf"):
#                 continue

#             min_costs[current_char] = current_cost

#             # Explore all possible conversions from the current character
#             for target_char, conversion_cost in adjacency_list[current_char]:
#                 new_total_cost = current_cost + conversion_cost

#                 # If we found a cheaper conversion, update its cost
#                 if min_costs[target_char] == float("inf"):
#                     heapq.heappush(
#                         priority_queue, (new_total_cost, target_char)
#                     )

#         # Return the list of minimum conversion costs from the starting character to all others
#         return min_costs
899