bfs 구현에 큐도 쓸줄 모르던 시절은 안녕~
package class3;
import java.util.*;
import java.io.*;
public class s1_1389{
static List<HashSet<Integer>> table = new ArrayList<>();
static Queue<Integer> q = new LinkedList<>();
static boolean[] check;
static int sum;
public static void main(String[] args){
FastScanner fs = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int N = fs.nextInt(), M = fs.nextInt();
check = new boolean[N + 1];
for (int i=0;i<N+1;i++) table.add(new HashSet<>());
for (int i=0;i<M;i++){
int a = fs.nextInt(), b = fs.nextInt();
table.get(a).add(b);
table.get(b).add(a);
}
int min = Integer.MAX_VALUE;
int num = 1;
for (int i=1;i<N+1;i++){
Arrays.fill(check, false);
check[i] = true;
q.add(i);
sum = 0;
bfs(0);
if (sum < min){
min = sum;
num = i;
}
}
pw.println(num);
pw.close();
}
static void bfs(int cnt){
int size = q.size();
if (size == 0) return;
for (int i=0;i<size;i++){
int node = q.poll();
sum += cnt;
for (Integer k : table.get(node)){
if (!check[k]){
check[k] = true;
q.add(k);
}
}
}
bfs(cnt + 1);
}
static void sort(int[] a){
ArrayList<Integer> L = new ArrayList<>();
for (int i : a) L.add(i);
Collections.sort(L);
for (int i = 0; i < a.length; i++) a[i] = L.get(i);
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next(){
while (!st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
int[] readArray(int n){
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong(){
return Long.parseLong(next());
}
}
}
'PS > Problems' 카테고리의 다른 글
[Java] 백준 1865번 웜홀 - 벨만-포드 알고리즘 (0) | 2022.01.08 |
---|---|
[Java] 백준 1753번 최단경로 - 다익스트라 (0) | 2022.01.08 |
[Java] 백준 1107번 리모컨 - 브루트포스 (0) | 2022.01.08 |
[Java] CodeForces Hello 2022 B.Integer shop (0) | 2022.01.04 |
[Java] 백준 24040번 예쁜 케이크 - 정수론 (0) | 2022.01.01 |