# 1135. Connecting Cities With Minimum Cost

{% hint style="info" %}
Kruskal Algorithm:

Union-Find and + sort edge by height, add edge if not connected

time: union-find for each vertex: O(1), total O(E); sort array: ElogE.

total O(ElogE+E)

space: O(V)
{% endhint %}

```java
// Some code
class Solution {
    int[] graph;
    int count;
    int cost;
    public int minimumCost(int n, int[][] connections) {
        graph = new int[n+1];
        for(int i=0; i<graph.length; i++){
            graph[i]=i;
        }
        count = n+1;
        
        Arrays.sort(connections, (a,b)->a[2]-b[2]);
        
        for(int[] edge : connections){
            if(!connected(edge[0], edge[1])){
                union(edge[0], edge[1]);
                cost+=edge[2];
            }
        }
        
        return count == 2 ? cost : -1;
    }
    
    private void union(int p, int q){
        int rootP = find(p);
        int rootQ = find(q);
        if(rootP!=rootQ){
            graph[rootP] = rootQ;
            count--;
        }
    }
    
    private boolean connected(int p, int q){
        int rootP = find(p);
        int rootQ = find(q);
        return rootP==rootQ;
    }
    
    private int find(int p){
        while(graph[p]!=p){
            graph[p]=graph[graph[p]];
            p=graph[p];
        }
        return p;
    }
}
```


---

# 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://ucan.gitbook.io/notes/graph/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.
