From 4116b08a53121e2f3f2a2348acdebd67a2b06bb9 Mon Sep 17 00:00:00 2001 From: oncsr Date: Tue, 24 Mar 2026 18:51:14 +0900 Subject: [PATCH] =?UTF-8?q?[20260324]=20BOJ=20/=20P2=20/=20Maximum=20Strat?= =?UTF-8?q?egic=20Savings=20/=20=EA=B6=8C=ED=98=81=EC=A4=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../24 BOJ P2 Maximum Strategic Savings.md | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 khj20006/202603/24 BOJ P2 Maximum Strategic Savings.md diff --git a/khj20006/202603/24 BOJ P2 Maximum Strategic Savings.md b/khj20006/202603/24 BOJ P2 Maximum Strategic Savings.md new file mode 100644 index 00000000..b1149d88 --- /dev/null +++ b/khj20006/202603/24 BOJ P2 Maximum Strategic Savings.md @@ -0,0 +1,89 @@ +```java +import java.io.*; +import java.util.*; + +public class BOJ16025 { + + static class DisjointSet { + int[] root; + DisjointSet(int size) { + root = new int[size+1]; + for(int i=1;i<=size;i++) { + root[i] = i; + } + } + + int find(int x) { + return x == root[x] ? x : (root[x] = find(root[x])); + } + + boolean union(int a, int b) { + int x = find(a), y = find(b); + if(x == y) { + return false; + } + root[x] = y; + return true; + } + } + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); + static StringTokenizer st; + + static int N, M, P, Q; + static int[][] edges; + static DisjointSet dsx, dsy; + + public static void main(String[] args) throws Exception { + st = new StringTokenizer(br.readLine()); + N = Integer.parseInt(st.nextToken()); + M = Integer.parseInt(st.nextToken()); + P = Integer.parseInt(st.nextToken()); + Q = Integer.parseInt(st.nextToken()); + + edges = new int[P+Q][]; + long sum = 0; + for(int i=0;i= P) { + type = 1; + sum += (long)c * M; + } + else { + sum += (long)c * N; + } + edges[i] = new int[]{a, b, c, type}; + } + + dsx = new DisjointSet(N); + dsy = new DisjointSet(M); + Arrays.sort(edges, (a,b) -> a[2]-b[2]); + long X = N, Y = M; + for(int[] edge : edges) { + int a = edge[0], b = edge[1], type = edge[3]; + long c = edge[2]; + + if(type == 0) { + if(dsy.union(a, b)) { + sum -= c * X; + Y--; + } + } + else { + if(dsx.union(a, b)) { + sum -= c * Y; + X--; + } + } + } + + bw.write(sum + "\n"); + bw.close(); + } +} +```