• 문제 링크
5014번: 스타트링크
첫째 줄에 F, S, G, U, D가 주어진다. (1 ≤ S, G ≤ F ≤ 1000000, 0 ≤ U, D ≤ 1000000) 건물은 1층부터 시작하고, 가장 높은 층은 F층이다.
www.acmicpc.net
• 풀이 과정
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int f, s, g, u, d;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
f = Integer.parseInt(st.nextToken());
s = Integer.parseInt(st.nextToken());
g = Integer.parseInt(st.nextToken());
u = Integer.parseInt(st.nextToken());
d = Integer.parseInt(st.nextToken());
int res = bfs();
bw.write(res == -1 ? "use the stairs" : String.valueOf(res));
bw.flush();
}
private static int bfs() {
Queue<Pair> q = new LinkedList<>();
boolean[] visit = new boolean[f + 1];
q.offer(new Pair(s, 0));
visit[s] = true;
while (!q.isEmpty()) {
Pair cur = q.poll();
int floor = cur.floor;
int cnt = cur.cnt;
if (floor == g)
return cnt;
if (floor + u <= f && !visit[floor + u]) {
visit[floor + u] = true;
q.offer(new Pair(floor + u, cnt + 1));
}
if (floor - d > 0 && !visit[floor - d]) {
visit[floor - d] = true;
q.offer(new Pair(floor - d, cnt + 1));
}
}
return -1;
}
private static class Pair {
int floor, cnt;
public Pair(int floor, int cnt) {
this.floor = floor;
this.cnt = cnt;
}
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 11048 이동하기 - Dynamic Programming / Java (0) | 2022.10.19 |
---|---|
[백준] 2579 계단 오르기 - Dynamic Programming / Java (0) | 2022.10.19 |
[백준] 14395 4연산 - Graph Theory / Java (0) | 2022.10.14 |
[백준] 10026 적록색약 - Graph Theory / Java (0) | 2022.10.13 |
[백준] 1963 소수 경로 - Graph Theory / Java (0) | 2022.10.12 |
댓글