Skip to content

Commit 4116b08

Browse files
authored
[20260324] BOJ / P2 / Maximum Strategic Savings / 권혁준
1 parent 3c5cc26 commit 4116b08

1 file changed

Lines changed: 89 additions & 0 deletions

File tree

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class BOJ16025 {
6+
7+
static class DisjointSet {
8+
int[] root;
9+
DisjointSet(int size) {
10+
root = new int[size+1];
11+
for(int i=1;i<=size;i++) {
12+
root[i] = i;
13+
}
14+
}
15+
16+
int find(int x) {
17+
return x == root[x] ? x : (root[x] = find(root[x]));
18+
}
19+
20+
boolean union(int a, int b) {
21+
int x = find(a), y = find(b);
22+
if(x == y) {
23+
return false;
24+
}
25+
root[x] = y;
26+
return true;
27+
}
28+
}
29+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
30+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
31+
static StringTokenizer st;
32+
33+
static int N, M, P, Q;
34+
static int[][] edges;
35+
static DisjointSet dsx, dsy;
36+
37+
public static void main(String[] args) throws Exception {
38+
st = new StringTokenizer(br.readLine());
39+
N = Integer.parseInt(st.nextToken());
40+
M = Integer.parseInt(st.nextToken());
41+
P = Integer.parseInt(st.nextToken());
42+
Q = Integer.parseInt(st.nextToken());
43+
44+
edges = new int[P+Q][];
45+
long sum = 0;
46+
for(int i=0;i<P+Q;i++) {
47+
st = new StringTokenizer(br.readLine());
48+
int a = Integer.parseInt(st.nextToken());
49+
int b = Integer.parseInt(st.nextToken());
50+
int c = Integer.parseInt(st.nextToken());
51+
52+
int type = 0;
53+
if(i >= P) {
54+
type = 1;
55+
sum += (long)c * M;
56+
}
57+
else {
58+
sum += (long)c * N;
59+
}
60+
edges[i] = new int[]{a, b, c, type};
61+
}
62+
63+
dsx = new DisjointSet(N);
64+
dsy = new DisjointSet(M);
65+
Arrays.sort(edges, (a,b) -> a[2]-b[2]);
66+
long X = N, Y = M;
67+
for(int[] edge : edges) {
68+
int a = edge[0], b = edge[1], type = edge[3];
69+
long c = edge[2];
70+
71+
if(type == 0) {
72+
if(dsy.union(a, b)) {
73+
sum -= c * X;
74+
Y--;
75+
}
76+
}
77+
else {
78+
if(dsx.union(a, b)) {
79+
sum -= c * Y;
80+
X--;
81+
}
82+
}
83+
}
84+
85+
bw.write(sum + "\n");
86+
bw.close();
87+
}
88+
}
89+
```

0 commit comments

Comments
 (0)