티스토리 뷰

출저 : https://www.acmicpc.net/problem/2839


"BFS를 이용한 탐색"



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
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
public class Main {
 
    static int N;
    static int min = -1;
    static int[] visited;
    static int[] weight = {3,5};
    static boolean ok;
    static Queue<Integer> q = new LinkedList<>();
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        
        visited = new int[N+1];
        Arrays.fill(visited, Integer.MAX_VALUE);
        
        q.add(0);
        q.add(0);
        
        while(!q.isEmpty()) {
            int cnt = q.poll();
            int sum = q.poll();
            
            if(sum == N) {
                min = cnt;
                break ;
            }
            
            for (int i = 0; i < 2; i++) {
                if(sum + weight[i] > N ||visited[sum+weight[i]] <= cnt+1)
                    continue;
                
                visited[sum+weight[i]] = cnt+1;
                q.add(cnt+1);
                q.add(sum+weight[i]);
            }
        }
        System.out.println(min);
    }
 
}
cs






댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday