Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Graphs

Make the Network Connected

Medium · Graphs · Asked at Amazon, Google, Microsoft

n computers are joined by m cables (u v). In one operation you can unplug any cable and plug it between any two computers. Print the minimum number of operations to connect all computers, or -1 if it is impossible.

Input

First line: n m. Next m lines: u v.

Output

The minimum number of operations, or -1.

Constraints

Connecting n computers needs at least n − 1 cables, so fewer means −1. Otherwise every extra cable inside a component can be moved, and you need exactly (number of components − 1) moves.

Example 1

Input

4 3
1 2
1 3
2 3

Output

1

Example 2

Input

6 4
1 2
1 3
1 4
1 5

Output

-1

Hints

  1. A connected network of n computers needs at least n − 1 cables.
  2. Inside a component, any cable beyond a spanning tree is spare and can be moved.
  3. Joining c components takes c − 1 moved cables.

Approach

If m < n − 1, print −1. Otherwise count connected components with a DSU (start with n, subtract one for each successful union). With m ≥ n − 1 there are always enough spare cables: each component of size s uses at most s − 1 cables in a spanning tree, so the spares are m − (n − c) ≥ c − 1. The answer is c − 1.

Complexity: O((n + m) α(n)) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

vector<int> parent;
int find(int x) {
    while (parent[x] != x) x = parent[x] = parent[parent[x]];
    return x;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m;
    cin >> n >> m;
    parent.resize(n + 1);
    iota(parent.begin(), parent.end(), 0);
    int comps = n;
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        int a = find(u), b = find(v);
        if (a != b) {
            parent[a] = b;
            comps--;
        }
    }
    cout << (m < n - 1 ? -1 : comps - 1) << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n, m = data[0], data[1]
parent = list(range(n + 1))


def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x


comps = n
for i in range(m):
    a, b = find(data[2 + 2 * i]), find(data[3 + 2 * i])
    if a != b:
        parent[a] = b
        comps -= 1
print(-1 if m < n - 1 else comps - 1)

Java solution

import java.io.*;

public class Main {
    static int[] parent;

    static int find(int x) {
        while (parent[x] != x) x = parent[x] = parent[parent[x]];
        return x;
    }

    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        in.nextToken();
        int m = (int) in.nval;
        parent = new int[n + 1];
        for (int i = 0; i <= n; i++) parent[i] = i;
        int comps = n;
        for (int i = 0; i < m; i++) {
            in.nextToken();
            int a = find((int) in.nval);
            in.nextToken();
            int b = find((int) in.nval);
            if (a != b) {
                parent[a] = b;
                comps--;
            }
        }
        System.out.println(m < n - 1 ? -1 : comps - 1);
    }
}

Solve Make the Network Connected online · All practice problems