Getting everything ready for you…

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

0s

Practice › Graphs

Minimum Cost to Connect All Points

Medium · Graphs · Asked at Amazon, Google, Microsoft, Directi

You are given n points on a plane. Connecting points (x1, y1) and (x2, y2) costs their Manhattan distance |x1 − x2| + |y1 − y2|. Print the minimum total cost to connect all points so that every pair is joined by some path.

Input

First line: n. Next n lines: x y.

Output

The minimum total cost.

Constraints

This is a minimum spanning tree on the complete graph. With n² edges, Prim’s algorithm with a plain array (O(n²), no heap) is the simplest fast choice. The total can exceed 2^31.

Example 1

Input

5
0 0
2 2
3 10
5 2
7 0

Output

20

Example 2

Input

3
3 12
-2 5
-4 1

Output

18

Hints

  1. You need a minimum spanning tree of the complete graph on the points.
  2. There are n² / 2 possible edges — too many to sort comfortably, but fine to scan.
  3. Prim’s algorithm with an array of "cheapest connection to the tree" runs in O(n²) without any heap.

Approach

Keep dist[v] = cheapest edge from v to the tree built so far (start with point 0 at distance 0). n times: pick the unused point with the smallest dist, add that cost, mark it used, and relax dist[v] for every unused v with the Manhattan distance to the new point. Every step scans all points, so the total work is O(n²) ≈ 10^6. The total can exceed 2^31.

Complexity: O(n²) time · O(n) space

Solution

C++ solution

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

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<long long> x(n), y(n);
    for (int i = 0; i < n; i++) cin >> x[i] >> y[i];
    vector<long long> dist(n, LLONG_MAX);
    vector<bool> used(n, false);
    dist[0] = 0;
    long long total = 0;
    for (int it = 0; it < n; it++) {
        int u = -1;
        for (int i = 0; i < n; i++)
            if (!used[i] && (u < 0 || dist[i] < dist[u])) u = i;
        used[u] = true;
        total += dist[u];
        for (int v = 0; v < n; v++)
            if (!used[v]) dist[v] = min(dist[v], llabs(x[u] - x[v]) + llabs(y[u] - y[v]));
    }
    cout << total << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
xs = data[1 : 1 + 2 * n : 2]
ys = data[2 : 2 + 2 * n : 2]
INF = float("inf")
dist = [INF] * n
used = [False] * n
dist[0] = 0
total = 0
for _ in range(n):
    u = min((i for i in range(n) if not used[i]), key=dist.__getitem__)
    used[u] = True
    total += dist[u]
    ux, uy = xs[u], ys[u]
    for v in range(n):
        if not used[v]:
            d = abs(ux - xs[v]) + abs(uy - ys[v])
            if d < dist[v]:
                dist[v] = d
print(total)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    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;
        long[] x = new long[n], y = new long[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            x[i] = (long) in.nval;
            in.nextToken();
            y[i] = (long) in.nval;
        }
        long[] dist = new long[n];
        Arrays.fill(dist, Long.MAX_VALUE);
        boolean[] used = new boolean[n];
        dist[0] = 0;
        long total = 0;
        for (int it = 0; it < n; it++) {
            int u = -1;
            for (int i = 0; i < n; i++)
                if (!used[i] && (u < 0 || dist[i] < dist[u])) u = i;
            used[u] = true;
            total += dist[u];
            for (int v = 0; v < n; v++)
                if (!used[v]) dist[v] = Math.min(dist[v], Math.abs(x[u] - x[v]) + Math.abs(y[u] - y[v]));
        }
        System.out.println(total);
    }
}

Solve Minimum Cost to Connect All Points online · All practice problems