๐ ๋ฌธ์
https://www.acmicpc.net/problem/13418
๐ ์์ด๋์ด
mst๋ฅผ ํ์ฉํ์ฌ ํ์ดํ์์ต๋๋ค.
*(๋ค๋ฅธ ๋ถ๋ค๊ณผ ํ์ด๊ฐ ๋ฌ๋ผ ๋ง๋ ํ์ด์ธ์ง ํ์ ์ด ๋ค์ง ์์ต๋๋ค. ์ฐธ๊ณ ๋ถํ๋๋ฆฝ๋๋ค)
๊ฐ์ฅ ํ์ด ๋๋๊ฒฝ์ฐ๋ ๊ฐ์ฅ ๋ง์ ๊ฒฝ์ฌ๋ก(๊ฐ์ ๊ธธ์ด ๋์ค์ง ์๊ธฐ๋๋ฌธ)๋ฅผ ์ด์ฉํ๋ ๊ฒฝ์ฐ๋ผ๊ณ ์๊ฐํ์์ต๋๋ค
๋ฐ๋ผ์ ๋จผ์ ๊ฒฝ์ฌ๋ก๋ฅผ ์ด์ฉํ๋ ๊ฒฝ์ฐ์ ๋ชจ๋ ๊ฒฝ๋ก๋ฅผ ์ฐ๊ฒฐํฉ๋๋ค. ์ด๋ ์ฐ๊ฒฐ๋ ๊ฒฝ์ฌ๋ก์ ๊ฐ์์ ์ ๊ณฑ์ด ์ ์๊ฐ ๋ฉ๋๋ค.
๊ฐ์ฅ ํ์ด ์ ๊ฒ ๋๋ ๊ฒฝ์ฐ๋ ๊ฒฝ์ฌ๋ก๋ฅผ ์ด์ฉํ์ง ์๊ณ ๋ด๋ฆฌ๋ง๊ธธ์ ๊ฐ์ฅ ๋ง์ด ์ด์ฉํด์ผ ํฉ๋๋ค.
์ด๋๋ ๋ง์ฝ unionํ๋ ๊ฒฝ์ฐ์ ์ฌ์ฉํ ๊ธธ์ ๊ฐ์์์ ๋นผ์ ๊ฒฝ์ฌ๋ก๋ก ๊ฐ์ผ๋ง ํ๋ ๊ธธ์ ๊ฐ์๋ฅผ ๊ตฌํ ์ ์์ต๋๋ค.
์ด๋ ๊ฒ ๊ตฌํ ๋๊ฐ์ ์ ์์ ์ฐจ๋ฅผ ๊ตฌํ์ฌ ์ ์ถํ์ฌ ํต๊ณผํ์์ต๋๋ค.
๐ ํ์ด
package ๋ฐฑ์ค.graph.mst.kruskal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Boj_13418_ํ๊ตํ๋ฐฉํ๊ธฐ {
private static class Road {
int start;
int end;
public Road(int start, int end) {
this.start = start;
this.end = end;
}
}
private static int[] parents;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken()) + 1; //city
int m = Integer.parseInt(st.nextToken()) + 1;
List<Road> slopes = new ArrayList<>(); //๊ฒฝ์ฌ๋ก๋ค๋ง
List<Road> descs = new ArrayList<>(); //๋ด๋ฆฌ๋ง๊ธธ๋ง
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
int slope = Integer.parseInt(st.nextToken());
if (slope == 0) {
slopes.add(new Road(start, end));
} else {
descs.add(new Road(start, end));
}
}
parents = new int[n];
//๊ฒฝ์ฌ๋ก ์ฐ๊ฒฐํ ์ ์๋ ๋งํผ ์ฐ๊ฒฐํ๋ ๊ฒฝ์ฐ
for (int i = 0; i < n; i++) {
parents[i] = i;
}
int maxCnt = 0;
for (Road slope : slopes) {
if (union(slope.start, slope.end)) {
maxCnt++;
}
}
//๋ด๋ ค๊ฐ๋ ๊ธธ์ ์ฐ๊ฒฐํ ์ ์๋ ๋งํผ ์ฐ๊ฒฐํ๋ ๊ฒฝ์ฐ
int minCnt= n-1;
for (int i = 0; i < n; i++) {
parents[i] = i;
}
for (Road desc : descs) {
if(union(desc.start, desc.end)){
minCnt--;
}
}
System.out.println((maxCnt * maxCnt) - (minCnt * minCnt));
}
private static boolean union(int a, int b) {
a = findParent(a);
b = findParent(b);
if (a != b) {
if (a < b) parents[b] = a;
else parents[a] = b;
return true;
}
return false;
}
private static int findParent(int a) {
if (a == parents[a]) return a;
return parents[a] = findParent(parents[a]);
}
}
'๋ฐฑ์ค(boj)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA]11437 LCA ๊ณตํต ๋ถ๋ชจ ๋ ธ๋ ์ฐพ๊ธฐ(๊ณจ๋ 3) (0) | 2023.09.20 |
---|---|
[JAVA]5427 ๋ถ ๊ณจ๋4 (0) | 2023.08.21 |
[JAVA]2531 ํ์ ์ด๋ฐฅ (0) | 2023.08.10 |
[JAVA]2230 ์ ๊ณ ๋ฅด๊ธฐ, ํฌ ํฌ์ธํฐ(๊ณจ๋5) (0) | 2023.08.09 |
[JAVA]11780 ํ๋ก์ด๋, ํ๋ก์ด๋ ์์ (1) | 2023.08.09 |