-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBOJ1389.java
More file actions
103 lines (85 loc) · 2.72 KB
/
BOJ1389.java
File metadata and controls
103 lines (85 loc) · 2.72 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BOJ1389 {
static int n, m;
static List<Integer>[] graph;
static int[][] kevinNum;
static boolean[] visited;
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
kevinNum = new int[n + 1][n + 1];
graph = new List[n + 1];
for (int i = 1; i <= n; i++) {
graph[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int friend1 = Integer.parseInt(st.nextToken());
int friend2 = Integer.parseInt(st.nextToken());
graph[friend1].add(friend2);
graph[friend2].add(friend1);
}
}
public static void main(String[] args) throws IOException {
input();
process();
}
private static void process() {
// bfs
for (int i = 1; i <= n; i++) {
visited = new boolean[n + 1];
kevinNum[i] = bfs(i);
}
// set answer
int kevinMinNum = Integer.MAX_VALUE;
int kevinMinVertex = -1;
for(int i = 1; i <= n; i++){
int sum = 0;
for(int j = 1; j <= n; j++){
sum += kevinNum[i][j];
}
if(sum < kevinMinNum){
kevinMinNum = sum;
kevinMinVertex = i;
}
}
// print answer
System.out.println(kevinMinVertex);
}
private static int[] bfs(int vertex) {
int[] answer = new int[n+1];
Queue<Integer> queue = new LinkedList<>();
queue.add(vertex);
visited[vertex] = true;
while(!queue.isEmpty()){
int thisVertex = queue.poll();
for(int i : graph[thisVertex]){
if(!visited[i]){
answer[i] = answer[thisVertex] + 1;
queue.add(i);
visited[i] = true;
}
}
}
return answer;
}
private static void printArray(int[][] array){
for(int i = 0 ; i < array.length; i++){
for(int j = 0 ; j < array[i].length; j++){
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
private static void printArray(int[] array){
for(int i = 0 ; i < array.length; i++){
System.out.print(array[i]);
}
System.out.println();
}
}