Post

[Algorithm] BOJ_1325_효율적인_해킹

BOJ_1325_효율적인_해킹 접근방식

[Algorithm] BOJ_1325_효율적인_해킹

BOJ_1325_효율적인_해킹

문제 링크

https://www.acmicpc.net/problem/1325

카테고리

그래프 BFS

접근 방식

각 노드 별로 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
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
75
76
77
78
79
80
81
82
83
84
85
86
package ver2.BOJ_1325_효율적인_해킹;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int n,v;
    static List<Integer>[] graph;
    private static int bfs(int start){
        boolean[] visited = new boolean[n+1];
        Queue<Integer> q = new LinkedList<>();
        q.offer(start);
        visited[start] = true;
        int rt = 0;

        while(!q.isEmpty()){
            int curr = q.poll();

            for(int next : graph[curr]){
                if(!visited[next]){
                    q.offer(next);
                    visited[next] = true;
                    rt++;
                }
            }
        }
        return rt;
    }
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] line = br.readLine().split(" ");
        n = Integer.parseInt(line[0]);
        v = Integer.parseInt(line[1]);

        graph = new ArrayList[n+1];

        int[] cnt = new int[n+1];
        int max = -1;

        for(int i = 1; i <= n; i++){
            graph[i] = new ArrayList<>();
        }

        for(int i = 0 ; i < v; i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int n1 = Integer.parseInt(st.nextToken());
            int n2 = Integer.parseInt(st.nextToken());

            graph[n2].add(n1);
        }

        for(int i = 1; i <= n; i++){
            int count = bfs(i);
            cnt[i] = count;
            max = Math.max(count,max);
        }

        List<Integer> ans = new ArrayList<>();

        for(int i = 1; i <= n; i++){
            if(cnt[i] == max) ans.add(i);
        }

        Collections.sort(ans);

        for(int i = 0 ; i < ans.size(); i++){
            System.out.print(ans.get(i) + " ");
        }

    }
}

/*
# 카테고리
그래프, BFS

# 접근 방식
각 노드 별로 BFS를 돌려 나오는 리턴값을 비교해서 값을 출력하는 방식이다.

# 문제 링크
https://www.acmicpc.net/problem/1325
 */
This post is licensed under CC BY 4.0 by the author.