D-Dimensional MST
You are given points in -dimensional space. The point has coordinates - .
Consider a weighted undirected complete graph with these points as its vertices. Weight of the edge between points and is .
Find the weight of the maximum spanning tree of this graph.
Input:
The first line contains two integers .
The -th of the next lines contains a description of the -th point. It has D integers: .
Output: Output a single line which contains a single integer - the Maximum Spanning Tree Weight
Constraints
Subtasks
10 points,
90 points,
Sample 1:
Input:
2 2
1 1
2 2
Output
2
Answer
import java.util.*;
class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt(), d = s.nextInt();
int[][] arr = new int[n][d];
for (int i = 0; i < n; i++) {
for (int j = 0; j < d; j++)
arr[i][j] = s.nextInt();
}
// Graph creation
int[][] graph = new int[n][n];
int[] key = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int wt = 0;
for (int k = 0; k < d; k++)
wt += Math.abs(arr[i][k] - arr[j][k]);
graph[i][j] = wt;
}
if (i != 0)
key[i] = Integer.MIN_VALUE;
}
Set<Integer> set = new HashSet<>();
long ans = 0;
while (set.size() != n) {
// Find the vertex with max key value & not in mst
// AKA find the min wt edge such that 1 vertex is in mst and the other is not
int max = -1;
int vertex = -1;
for (int i = 0; i < n; i++) {
if (!set.contains(i) && key[i] > max) {
max = key[i];
vertex = i;
}
}
set.add(vertex);
ans += max;
for (int i = 0; i < n; i++) {
if (!set.contains(i)) {
key[i] = Math.max(key[i], graph[vertex][i]);
}
}
}
System.out.println(ans);
}
}
Last updated