Repository navigation
Expand file tree
/
Copy pathMST - Kruskals.java
More file actions
75 lines (65 loc) · 1.78 KB
/
Copy pathMST - Kruskals.java
File metadata and controls
75 lines (65 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// https://cses.fi/problemset/task/1675/
import java.util.*;
public class Main{
static int n,m;
static int[] parent;
static int[] setSize;
static int[][] edges;
static void makeSet(int node){
parent[node]=node;
setSize[node]=1;
}
static int findSet(int node){
if(node==parent[node]) return node;
return parent[node]=findSet(parent[node]);
}
static void unionSets(int a, int b){
a=findSet(a);
b=findSet(b);
if(a!=b){
if(setSize[a]>setSize[b]){
parent[b]=a;
setSize[a]+=setSize[b];
}else{
parent[a]=b;
setSize[b]+=setSize[a];
}
}
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
parent = new int[n+1];
edges = new int[m][3];
setSize = new int[n+1];
for(int i=0;i<m;i++){
int a = sc.nextInt();
int b = sc.nextInt();
int wt = sc.nextInt();
edges[i][0]=wt;
edges[i][1]=a;
edges[i][2]=b;
}
Arrays.sort(edges, Comparator.comparingInt(a -> a[0]));
for(int i=1;i<=n;i++) makeSet(i);
long totalCost=0;
int edgecount=0;
for(int[] edge:edges){
int cost=edge[0];
int u=edge[1];
int v=edge[2];
if(findSet(u)!=findSet(v)){
unionSets(u,v);
totalCost+=cost;
edgecount++;
if(edgecount==n-1) break;
}
}
if(edgecount==n-1){
System.out.println(totalCost);
}else{
System.out.println("IMPOSSIBLE");
}
}
}