[BaekJoon] #5567 - 결혼식 [Java][C++]
[BaekJoon] #5567 - 결혼식 [Java][C++]
1. 아이디어
초대할 사람은 상근이의 친구와 친구의 친구까지다. 상근이를 기준으로 거리가 2 이내인 모든 사람의 수를 구하면 되므로 최단 거리 BFS를 활용해서 개수를 세었다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N + M)$ | $O(N + M)$ |
($N$ = 입력값 n, $M$ = 입력값 m)
3. 코드
풀이 [Java][C++]
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
import java.io.*;
import java.util.*;
public class Main {
static int n;
static List<Integer>[] adj;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
n = Integer.parseInt(br.readLine());
int m = Integer.parseInt(br.readLine());
adj = new ArrayList[1 + n];
for (int i = 1; i <= n; i++) {
adj[i] = new ArrayList<>();
}
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
adj[u].add(v);
adj[v].add(u);
}
System.out.println(bfs());
}
static int bfs() {
Queue<Integer> q = new ArrayDeque<>();
q.offer(1);
boolean[] vis = new boolean[1 + n];
vis[1] = true;
int dist = 0;
int cnt = 0;
while (!q.isEmpty()) {
int sz = q.size();
while (sz-- > 0) {
int cur = q.poll();
for (int nxt : adj[cur]) {
if (vis[nxt]) continue;
q.offer(nxt);
vis[nxt] = true;
cnt++;
}
}
dist++;
if (dist == 2) break;
}
return cnt;
}
}
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
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1 + 500;
int n;
vector<int> adj[MAX_N];
bool vis[MAX_N];
int bfs() {
queue<int> q;
q.push(1);
vis[1] = true;
int dist = 0;
int cnt = 0;
while (!q.empty()) {
int sz = q.size();
while (sz--) {
int cur = q.front();
q.pop();
for (int nxt : adj[cur]) {
if (vis[nxt]) continue;
q.push(nxt);
vis[nxt] = true;
cnt++;
}
}
dist++;
if (dist == 2) break;
}
return cnt;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int m;
cin >> n >> m;
while (m--) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
cout << bfs();
}
This post is licensed under CC BY 4.0 by the author.