File tree Expand file tree Collapse file tree 1 file changed +34
-22
lines changed Expand file tree Collapse file tree 1 file changed +34
-22
lines changed Original file line number Diff line number Diff line change 1
- // Authored by : yongjunleeme
2
- // Co-authored by : BaaaaaaaaaaarkingDog
3
- // http://boj.kr/65c65de75cb34088b63463ec29b4e92a
1
+ // Authored by : BaaaaaaaaaaarkingDog
2
+ // Co-authored by : -
3
+ // http://boj.kr/4de63bcfae1f4c529037d0b03050a65d
4
4
#include < bits/stdc++.h>
5
5
using namespace std ;
6
6
7
7
int n, m, a, b;
8
8
vector <int > adj[505 ];
9
- int vis[505 ];
10
- int ans = 0 ;
11
-
12
- void dfs (){
13
- stack<int > s;
14
- s.push (1 );
15
- while (!s.empty ()){
16
- int cur = s.top (); s.pop ();
17
- vis[cur] = 1 ;
18
- for (auto nxt : adj[cur]){
19
- if (vis[nxt]) continue ;
20
- vis[nxt] = 1 ;
21
- ans++;
22
- if (cur == 1 ) s.push (nxt); // 상근이의 이웃만 스택에 추가됨
23
- }
24
- }
25
- }
9
+ int dist[505 ];
26
10
27
11
int main (void ){
28
12
ios::sync_with_stdio (0 );
@@ -35,6 +19,34 @@ int main(void){
35
19
adj[b].push_back (a);
36
20
}
37
21
38
- dfs ();
39
- cout << ans;
22
+ int ans = 0 ;
23
+ queue<int > q;
24
+ q.push (1 );
25
+ dist[1 ] = 1 ;
26
+ while (!q.empty ()){
27
+ int cur = q.front ();
28
+ q.pop ();
29
+ if (dist[cur] > 2 ) // 친구의 친구는 거기서 bfs를 더 하지 않고 stop
30
+ continue ;
31
+ for (auto nxt : adj[cur]){
32
+ if (dist[nxt] > 0 )
33
+ continue ;
34
+ dist[nxt] = dist[cur] + 1 ;
35
+ q.push (nxt);
36
+ ans++;
37
+ }
38
+ }
39
+ cout << ans << ' \n ' ;
40
40
}
41
+
42
+ /*
43
+ DFS로 풀이를 해도 괜찮지만 그 경우에는 같은 사람이 친구이자 친구의 친구인 경우의 처리에 주의.
44
+ ex)
45
+ 1-2
46
+ 1-3
47
+ 2-3
48
+ 3-4
49
+ 3-5
50
+ 에서는 3이 상근이의 친구이자 친구의 친구임. 이 때 처리를 잘못하면
51
+ 자칫 4, 5를 포함시키지 않을 수도 있음.
52
+ */
You can’t perform that action at this time.
0 commit comments