# 유형 : BFS + 시뮬레이션

# 난이도 : 실버4 

# 현 위치 기준 +1, -1, +A, -A, +B, -B, *A, *B 8가지를 인덱스 주의하며 탐색을 돌려주면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package bj;
 
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class p12761 {
    static int A,B,N,M, result=0;
    static boolean visit[] = new boolean[100001];
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        A = Integer.parseInt(st.nextToken());
        B = Integer.parseInt(st.nextToken());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        
        bfs();
        System.out.println(result);
    }
    private static void bfs() {
        // TODO Auto-generated method stub
        Queue<Point> queue = new LinkedList<Point>();
        queue.add(new Point(N,0));
        visit[N] = true;
        while(!queue.isEmpty()) {
            
            Point po = queue.poll();
            
            if(po.x == M) {
                result = po.y;
                return;
            }
            
            if(po.x + 1 < 100001 && !visit[po.x+1]) {
                visit[po.x+1= true;
                queue.add(new Point(po.x+1, po.y+1));
            }
            if(po.x - 1 >= 0 && !visit[po.x-1]) {
                visit[po.x-1= true;
                queue.add(new Point(po.x-1, po.y+1));
            }
            if(po.x + A < 100001 && !visit[po.x+A]) {
                visit[po.x+A] = true;
                queue.add(new Point(po.x+A, po.y+1));
            }
            if(po.x - A >= 0 && !visit[po.x-A]) {
                visit[po.x-A] = true;
                queue.add(new Point(po.x-A, po.y+1));
            }
            if(po.x + B < 100001 && !visit[po.x+B]) {
                visit[po.x+B] = true;
                queue.add(new Point(po.x+B, po.y+1));
            }
            if(po.x - B >= 0 && !visit[po.x-B]) {
                visit[po.x-B] = true;
                queue.add(new Point(po.x-B, po.y+1));
            }
            if(po.x * A < 100001 && !visit[po.x*A]) {
                visit[po.x*A] = true;
                queue.add(new Point(po.x*A, po.y+1));
            }
            if(po.x * B < 100001 && !visit[po.x*B]) {
                visit[po.x*B] = true;
                queue.add(new Point(po.x*B, po.y+1));
            }
        }
    }
}
 
cs

+ Recent posts