forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1.cpp
More file actions
53 lines (45 loc) Β· 1.38 KB
/
1.cpp
File metadata and controls
53 lines (45 loc) Β· 1.38 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
#include <bits/stdc++.h>
using namespace std;
// λμμ κ°μ, λλ‘μ κ°μ, 거리 μ 보, μΆλ° λμ λ²νΈ
int n, m, k, x;
vector<int> graph[300001];
// λͺ¨λ λμμ λν μ΅λ¨ 거리 μ΄κΈ°ν
vector<int> d(300001, -1);
int main(void) {
cin >> n >> m >> k >> x;
// λͺ¨λ λλ‘ μ 보 μ
λ ₯ λ°κΈ°
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
}
// μΆλ° λμκΉμ§μ 거리λ 0μΌλ‘ μ€μ
d[x] = 0;
// λλΉ μ°μ νμ(BFS) μν
queue<int> q;
q.push(x);
while (!q.empty()) {
int now = q.front();
q.pop();
// νμ¬ λμμμ μ΄λν μ μλ λͺ¨λ λμλ₯Ό νμΈ
for (int i = 0; i < graph[now].size(); i++) {
int nextNode = graph[now][i];
// μμ§ λ°©λ¬Ένμ§ μμ λμλΌλ©΄
if (d[nextNode] == -1) {
// μ΅λ¨ 거리 κ°±μ
d[nextNode] = d[now] + 1;
q.push(nextNode);
}
}
}
// μ΅λ¨ κ±°λ¦¬κ° KμΈ λͺ¨λ λμμ λ²νΈλ₯Ό μ€λ¦μ°¨μμΌλ‘ μΆλ ₯
bool check = false;
for (int i = 1; i <= n; i++) {
if (d[i] == k) {
cout << i << '\n';
check = true;
}
}
// λ§μ½ μ΅λ¨ κ±°λ¦¬κ° KμΈ λμκ° μλ€λ©΄, -1 μΆλ ₯
if (!check) cout << -1 << '\n';
}