-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathA.java
128 lines (109 loc) · 3.31 KB
/
A.java
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import javafx.util.Pair;
import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
public class Main {
private FastScanner in;
private PrintWriter out;
private int n, m;
private ArrayList<Pair<Pair<Integer, Integer>, Integer>> edges = new ArrayList<>();
int cost = 0;
int[] parent = new int[20000];
int[] rank = new int[20000];
private void make_set(int v) {
parent[v] = v;
rank[v] = 0;
}
private int find_set(int v) {
if (v == parent[v]) {
return v;
}
return parent[v] = find_set(parent[v]);
}
private void union_sets(int a, int b) {
a = find_set(a);
b = find_set(b);
if (a != b) {
if (rank[a] < rank[b]) {
int c = b;
b = a;
a = c;
}
parent[b] = a;
if (rank[a] == rank[b]) {
rank[a]++;
}
}
}
public class CustomComparator implements Comparator<Pair<Pair<Integer, Integer>, Integer>> {
@Override
public int compare(Pair<Pair<Integer, Integer>, Integer> o1, Pair<Pair<Integer, Integer>, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}
private void input() throws IOException {
n = in.nextInt();
m = in.nextInt();
for (int i = 0; i < m; i++) {
edges.add(new Pair<>(new Pair<>(in.nextInt(), in.nextInt()), in.nextInt()));
}
edges.sort(new CustomComparator());
for (int i = 0; i < n; i++) {
make_set(i);
}
}
private void solve() throws IOException {
input();
for (int i = 0; i < m; i++) {
int from = edges.get(i).getKey().getKey();
int to = edges.get(i).getKey().getValue();
int w = edges.get(i).getValue();
if (find_set(from) != find_set(to)) {
cost += w;
union_sets(from, to);
}
}
output();
}
private void output() throws IOException {
out.print(cost);
}
private void run() {
try {
String fileName = "spantree2";
in = new FastScanner(new File(fileName + ".in"));
out = new PrintWriter(new File(fileName + ".out")); // PrintWriter(System.out) || new File("output" + ".out")
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f)); //InputStreamReader(System.in) || new FileReader(f)
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] arg) {
new Main().run();
}
}