Skip to content

Commit 5d74bf5

Browse files
authored
[20250903] BOJ / G1 / K-지폐 / 한종욱
1 parent ef5cf46 commit 5d74bf5

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

Ukj0ng/202509/3 BOJ G1 K-지폐.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
```
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
private static final long INF = (long) 1e15 + 10;
9+
private static List<Edge>[] graph;
10+
private static long[][] dist;
11+
private static int N, M, K, S, T;
12+
13+
public static void main(String[] args) throws IOException {
14+
init();
15+
dijkstra(S);
16+
17+
long answer = -1;
18+
if (dist[T][0] != INF) {
19+
answer = dist[T][0];
20+
}
21+
22+
if (answer == -1) bw.write("IMPOSSIBLE" + "\n");
23+
else bw.write(answer + "\n");
24+
bw.flush();
25+
bw.close();
26+
br.close();
27+
}
28+
29+
private static void init() throws IOException {
30+
StringTokenizer st = new StringTokenizer(br.readLine());
31+
N = Integer.parseInt(st.nextToken());
32+
M = Integer.parseInt(st.nextToken());
33+
K = Integer.parseInt(st.nextToken());
34+
35+
st = new StringTokenizer(br.readLine());
36+
S = Integer.parseInt(st.nextToken());
37+
T = Integer.parseInt(st.nextToken());
38+
39+
graph = new List[N + 1];
40+
dist = new long[N + 1][K];
41+
42+
for (int i = 1; i <= N; i++) {
43+
graph[i] = new ArrayList<>();
44+
}
45+
46+
for (int i = 0; i < M; i++) {
47+
st = new StringTokenizer(br.readLine());
48+
int a = Integer.parseInt(st.nextToken());
49+
int b = Integer.parseInt(st.nextToken());
50+
long cost = Long.parseLong(st.nextToken());
51+
52+
graph[a].add(new Edge(b, cost));
53+
}
54+
}
55+
56+
private static void dijkstra(int start) {
57+
PriorityQueue<Edge> pq = new PriorityQueue<>((o1, o2) -> Long.compare(o1.cost, o2.cost));
58+
for (int i = 1; i <= N; i++) {
59+
Arrays.fill(dist[i], INF);
60+
}
61+
dist[start][0] = 0;
62+
pq.add(new Edge(start, 0, 0));
63+
64+
while (!pq.isEmpty()) {
65+
Edge current = pq.poll();
66+
67+
if (current.cost > dist[current.dest][current.state]) continue;
68+
69+
for (Edge next : graph[current.dest]) {
70+
long nCost = current.cost + next.cost;
71+
int nState = (int) (nCost % K);
72+
73+
if (nCost < dist[next.dest][nState]) {
74+
dist[next.dest][nState] = nCost;
75+
pq.add(new Edge(next.dest, dist[next.dest][nState], nState));
76+
}
77+
}
78+
}
79+
}
80+
81+
static class Edge {
82+
int dest;
83+
long cost;
84+
int state;
85+
86+
public Edge(int dest, long cost, int state) {
87+
this.dest = dest;
88+
this.cost = cost;
89+
this.state = state;
90+
}
91+
92+
public Edge(int dest, long cost) {
93+
this.dest = dest;
94+
this.cost = cost;
95+
this.state = 0;
96+
}
97+
}
98+
}
99+
```

0 commit comments

Comments
 (0)