-
[24445] 알고리즘 수업 - 너비 우선 탐색 2BOJ 2022. 5. 2. 02:02
https://www.acmicpc.net/problem/24445
24445번: 알고리즘 수업 - 너비 우선 탐색 2
첫째 줄에 정점의 수 N (5 ≤ N ≤ 100,000), 간선의 수 M (1 ≤ M ≤ 200,000), 시작 정점 R (1 ≤ R ≤ N)이 주어진다. 다음 M개 줄에 간선 정보 u v가 주어지며 정점 u와 정점 v의 가중치 1인 양
www.acmicpc.net
인접리스트를 역순으로 정렬해두고 실제로 bfs를 돌리면서 순서를 기록해두자
#include <bits/stdc++.h>using namespace std;#ifdef ONLINE_JUDGEconstexpr bool local = false;#elseconstexpr bool local = true;#endifusing ll = long long;using pi = pair<ll, ll>;int n, m, s, vst[100001];queue<int> q;vector<int> adj[100001];int main(void) {if (!local) ios_base::sync_with_stdio(0), cin.tie(0);cin >> n >> m >> s;int i;for (i = 0; i < m; i++) {int A, B;cin >> A >> B;adj[A].push_back(B);adj[B].push_back(A);}for (i = 1; i <= n; i++) sort(adj[i].begin(), adj[i].end(), greater<>());vst[s] = 1;q.push(s);int cnt = 2;while (!q.empty()) {int cur = q.front();q.pop();for (int& nxt : adj[cur]) {if (vst[nxt] == 0) {vst[nxt] = cnt++;q.push(nxt);}}}for (i = 1; i <= n; i++) cout << vst[i] << '\n';return 0;}
'BOJ' 카테고리의 다른 글
[2312] 수 복원하기 (0) 2022.05.02 [1283] 단축키 지정 (0) 2022.05.02 [15967] 에바쿰 (0) 2022.05.02 [13900] 순서쌍의 곱의 합 (0) 2022.04.27 [2784] 가로 세로 퍼즐 (0) 2022.04.27