[๋ฐฑ์ค, Java] 10775๋ฒ : ๊ณตํญ
๐ ๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/10775
๐ฎ ๋ฌธ์ ํด๊ฒฐ ๋ฐฉ๋ฒ
๋ฌธ์ ์์ ๋นํ๊ธฐ๊ฐ ์์๋๋ก ๋์ฐฉํ ์์ ์ด๊ณ ๊ฐ ๋นํ๊ธฐ์ ๊ฐ์ 1๋ถํฐ ํด๋น ๊ฐ๊น์ง์ ๊ฒ์ดํธ์ ๋ํนํ ์ ์๋ ๊ฒ์ ์๋ฏธํ๋ค.
์์ ์ ์์์ ๋นํ๊ธฐ๊ฐ ๋ํนํ ์ ์์ ๋๊น์ง ๊ฐ์๋ฅผ ์ธ์ค๋ค.
๋นํ๊ธฐ๊ฐ ๋ํนํ ์ ์๋ ๊ฒ์ดํธ๋ฅผ ์ฐพ๊ธฐ ์ํด์ Union-Find๋ฅผ ์ด์ฉํ๋ค.
๊ฒ์ดํธ ๋ฐฐ์ด์ ์์ ์ ๊ฒ์ดํธ๋ก ์ด๊ธฐํ๋ฅผ ํ๊ณ , ํด๋น ๊ฐ์ ๋นํ๊ธฐ๊ฐ ๋ํน๋๋ฉด ๋ค์์ ๋ํน๋ ๋์ผํ ๊ฐ์ ๋นํ๊ธฐ๋ ํ์ฌ ๊ฒ์ดํธ๋ณด๋ค ํ๋ ์์ ๊ฒ์ดํธ๋ก ๋ํน๋์ด์ผ ํ๋ค.
์๋ฅผ ๋ค์ด, ๊ฒ์ดํธ๊ฐ 4๊ฐ์ด๊ณ ์๋ฌด ๋นํ๊ธฐ๋ ๊ฒ์ดํธ์ ๋ํน๋์ง ์์๋ค๋ฉด ๊ฒ์ดํธ ๋ฐฐ์ด์ 1,2,3,4๊ฐ์ ๊ฐ์ง ๊ฒ์ด๋ค.
3๋ฒ ๋นํ๊ธฐ๊ฐ 3๋ฒ ๊ฒ์ดํธ์ ๋ํน๋๋ฉด ์ด ํ์ ๋ค์ด์ค๋ 3๋ฒ ๋นํ๊ธฐ๋ 1 ์๋๋ฉด 2๋ฒ ๊ฒ์ดํธ์ ๋ํน๋์ด์ผ ํ๋ค. 2๋ฒ ๊ฒ์ดํธ๋ก ๋ค์ด์ฌ ๋ ๋ํน๋ ์ ์๋ ๊ฒ์ดํธ์ 3๋ฒ ๊ฒ์ดํธ๋ก ๋ค์ด์ฌ ๋ ๋ํน๋ ์ ์๋ ๊ฒ์ดํธ๋ฅผ ํฉ์ณ์ค๋ค.
์ด ๋, Union - Find๋ฅผ ์ด์ฉํด ๋ค์ ๋ํน๋ ๊ฒ์ดํธ๋ฅผ ์งํฉ์ผ๋ก ํฉ์ณ์ค๋ค
- ํ์ฌ ์ด์ฉ ๊ฐ๋ฅํ ๊ฐ์ฅ ํฐ ๊ฒ์ดํธ๋ฅผ find ์ฐ์ฐ์ ํตํด ์ฐพ๋๋ค.
- ๋ง์ฝ ์ฐพ์ ๊ฒ์ดํธ๊ฐ 0๋ฒ ๊ฒ์ดํธ๋ผ๋ฉด (๋ํนํ ์ ์๋ ๊ฒฝ์ฐ) ๋ฐ๋ณต๋ฌธ์ ํ์ถํ๋ค .
- ํ์ฌ ์ด์ฉ ๊ฐ๋ฅํ ๊ฐ์ฅ ํฐ ๊ฒ์ดํธ๋ฅผ ์ด์ฉํ๋ค๋ฉด, ํ์ฌ ์ด์ฉํ ๊ฒ์ดํธ์ ๋ค์๋ฒ์ ๋์ผํ ๊ฐ์ ๊ฐ์ง ๋นํ๊ธฐ๊ฐ ๋ํนํ ๊ฒ์ดํธ (ํ์ฌ ์ด์ฉํ ๊ฒ์ดํธ -1)๊ณผ Union์ฐ์ฐ์ ํตํด ๋ค์ ๋ํนํ ๊ฒ์ดํธ๋ฅผ ๋ง๋ค์ด์ค๋ค.
๐ฉ Java ์ฝ๋
package com.algorithm.Baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main_10775_๊ณตํญ {
private static List<Integer> plane;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int G = Integer.parseInt(br.readLine());
int P = Integer.parseInt(br.readLine());
plane = new ArrayList<>();
for (int airplane = 0; airplane < P; airplane++) {
plane.add(Integer.parseInt(br.readLine()));
}
int rst = dockingAirplane(G, P);
System.out.println(rst);
br.close();
}
private static int dockingAirplane(int g, int p) {
int[] gates = new int[g + 1];
for (int gate = 1; gate <= g; gate++) {
gates[gate] = gate;
}
int count = 0;
for (Integer airplane : plane) {
// ์ด์ฉ๊ฐ๋ฅํ ๊ฒ์ดํธ ์ฐพ๊ธฐ
int availableGate = find(gates, airplane);
// ์ด์ฉ ๊ฐ๋ฅํ ๊ฒ์ดํธ๊ฐ ์๋ค๋ฉด ๋ฐ๋ณต๋ฌธ ํ์ถ
if(availableGate < 1) break;
// ๊ฒ์ดํธ์ ๋ฐฐ์น ํ์ผ๋ ํ์ฌ ๋นํ๊ธฐ์ ๋์ผํ ๊ฒ์ดํธ ๋ฒํธ๋ฅผ ๊ฐ์ง ๋นํ๊ธฐ ๋ํน ์ ํ์ฌ ๊ฒ์ดํธ๋ณด๋ค ํ๋ ์์ ๊ฒ์ดํธ๋ฅผ ์ด์ฉ ํ์
union(airplane, availableGate - 1, gates);
count++;
}
return count;
}
private static void union(Integer airplane, int nextAvailable, int[] gates) {
int curGate = find(gates, airplane); // ํ์ฌ ๋นํ๊ธฐ๊ฐ ์ด์ฉ์ค์ธ ๊ฒ์ดํธ ์ฐพ๊ธฐ
int nextGate = find(gates, nextAvailable); // ๋์ผํ ๊ฒ์ดํธ ๋ฒํธ ๋นํ๊ธฐ๊ฐ ๋ค์์ ๋ํน์ ์ฌ์ฉํ ๊ฒ์ดํธ ์ฐพ๊ธฐ
if(curGate > nextGate) gates[curGate] = nextGate;
else gates[nextGate] = curGate;
}
private static int find(int[] gates, Integer airplane) {
if(gates[airplane] != airplane) gates[airplane] = find(gates, gates[airplane]);
return gates[airplane];
}
}