Problem ๐ป
๊ฒฐ์ ๋ฌธ์ ๋ก ์ด๋ถํ์ + ๋ค์ต์คํธ๋ผ or BFS, DFS๋ก ํ ์ ์๋ ๋ฌธ์ ์ด๋ค.
์ปดํจํฐ N๊ฐ๋ฅผ ์ฐ๊ฒฐํ๋ ์ต์ ๋น์ฉ์ ๊ตฌํ๋๋ฐ, ์ด๋ค ๋น์ฉ X์ ๋ํ์ฌ ํด๋น ๋น์ฉ X๋ณด๋ค ์์ผ๋ฉด ๋์ ๋ด๊ณ , ํฌ๋ฉด ๋ฌด๋ฃ๋ก ์ฐ๊ฒฐํ์ฌ ์ต์ ๋น์ฉ์ ๊ตฌํ๋๋ก ๋ฌธ์ ์ ์๊ตฌ ์กฐ๊ฑด์ ๋ฐ๊พธ๋ฉด ๋๋ค.
Approach 1 โญ
- ์ด๋ถํ์ + ๋ค์ต์คํธ๋ผ
์ด๋ถํ์์ ํตํ์ฌ ์ต์ํ์ผ๋ก ๋ด์ผํ ๊ธ์ก์ ๊ฒฐ์ ํ๊ณ , ๋ค์ต์คํธ๋ผ๋ฅผ ํตํด ๋ฌด๋ฃ๋ก ์ฐ๊ฒฐํ ํ์๋ฅผ ๊ฐ์ค์น๋ก ํ์ฌ 1 → N ์ปดํจํฐ๋ก์ ์ต์ ๋ฌด๋ฃ ์ฐ๊ฒฐ ํ์๋ฅผ ๊ตฌํ ๋ค์ ํด๋น ํ์๊ฐ k๋ฅผ ๋๋์ง ํ์ธํ๋ฉด ๋๋ค.
k๋ฅผ ๋๋๋ค๋ฉด ์ฐ๊ฒฐํ ์ ์๋ ๊ฒฝ์ฐ์ด๋ฏ๋ก ๋ค์ ๋น์ฉ์ ๋ ์ฆ๊ฐ์์ผ๋ณด๊ณ , k๋ฅผ ๋์ง ์๊ฑฐ๋ ๊ฐ๋ค๋ฉด ๋น์ฉ์ ๋ ์ค์ผ ์ ์๋์ง๋ฅผ ํ์ธํ๋ค. ๊ทธ๋ ๊ฒํด์ ์์ ๋ฅผ ๋ณด๋ฉด ์ต์ 4์ ๋น์ฉ์ ๋์ด์ผ 1 → N์ผ๋ก ๊ฐ ์ ์๋ค๋ ๊ฒฐ๋ก ์ด ๋์จ๋ค.
Solution ๐ก
public class BOJ_1800 {
private static int n, p, k;
private static ArrayList<ArrayList<Vertex>> graph;
static class Vertex implements Comparable<Vertex> {
int v, w;
public Vertex(int v, int w) {
this.v = v;
this.w = w;
}
@Override
public int compareTo(Vertex o) {
return this.w - o.w;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
p = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
graph = new ArrayList<>();
for (int i = 0; i <= n; i++) graph.add(new ArrayList<>());
for (int i = 0; i < p; i++) {
st = new StringTokenizer(br.readLine());
int v1 = Integer.parseInt(st.nextToken());
int v2 = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
graph.get(v1).add(new Vertex(v2, w));
graph.get(v2).add(new Vertex(v1, w));
}
int ans = -1;
int left = 0;
int right = 1_000_001;
while (left <= right) {
int mid = (left + right) / 2;
if (dijkstra(mid)) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
System.out.println(ans);
}
private static boolean dijkstra(int x) {
PriorityQueue<Vertex> pq = new PriorityQueue<>();
pq.add(new Vertex(1, 0));
int[] shortest = new int[n+1];
Arrays.fill(shortest, Integer.MAX_VALUE);
shortest[1] = 0;
while (!pq.isEmpty()) {
Vertex vertex = pq.poll();
if (shortest[vertex.v] < vertex.w) continue;
for (int idx = 0; idx < graph.get(vertex.v).size(); idx++) {
int nextValue = vertex.w;
Vertex next = graph.get(vertex.v).get(idx);
if (next.w > x)
nextValue++;
if (nextValue < shortest[next.v]) {
shortest[next.v] = nextValue;
pq.add(new Vertex(next.v, nextValue));
}
}
}
return shortest[n] <= k;
}
}
Reference ๐
https://dlwnsdud205.tistory.com/205
https://justicehui.github.io/usaco/2019/07/12/BOJ1800/
'์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
10875. ๋ฑ (0) | 2025.02.05 |
---|---|
14658. ํ๋์์ ๋ณ๋ฅ๋ณ์ด ๋น๋ฐ์น๋ค (0) | 2025.01.29 |
1863. ์ค์นด์ด๋ผ์ธ ์ฌ์ด๊ฑฐ (0) | 2025.01.22 |
4485. ๋ น์ ์ท ์ ์ ์ ๊ฐ ์ ค๋ค์ง? (0) | 2025.01.19 |
1238. ํํฐ (0) | 2025.01.17 |