# 1135. Connecting Cities With Minimum Cost

O(ElogE)

````java
```java
class Solution {
    class Step {
        int id;
        int cost;
        Step(int id, int cost) {
            this.id = id;
            this.cost = cost;
        }
    }
    public int minimumCost(int n, int[][] connections) {
        Map<Integer, List<Step>> graph = buildGraph(connections);
        Queue<Step> pq = new PriorityQueue<>((a, b) -> a.cost - b.cost);
        pq.offer(new Step(1, 0)); // id start from 1
        Set<Integer> visited = new HashSet<>();

        int result = 0;
        while (!pq.isEmpty()) {
            Step cur = pq.poll();

            if (visited.contains(cur.id)) {
                continue;
            }
            visited.add(cur.id);
            result += cur.cost;

            if (visited.size() == n) {
                return result;
            }
            if (graph.containsKey(cur.id)) {
                for (Step next : graph.get(cur.id)) {
                    pq.offer(next);
                }
            }
        }
        return -1;
    }
    private Map<Integer, List<Step>> buildGraph(int[][] connections) {
        Map<Integer, List<Step>> graph = new HashMap<>();
        for (int[] c : connections) {
            graph.putIfAbsent(c[0], new ArrayList<>());
            graph.get(c[0]).add(new Step(c[1], c[2]));

            graph.putIfAbsent(c[1], new ArrayList<>());
            graph.get(c[1]).add(new Step(c[0], c[2]));
        }
        return graph;
    }
}
```
````


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dfs-and-bfs/graph-ii/mst-prims-algo/1135.-connecting-cities-with-minimum-cost.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
