티스토리 뷰

문제 출처: https://www.acmicpc.net/problem/24446

 

24446번: 알고리즘 수업 - 너비 우선 탐색 3

너비 우선 탐색 트리는 1, 2, 3, 4번 노드로 구성된다. 1번 노드가 루트이다. 1번 노드의 자식은 2, 4번 노드이다. 3번 노드는 2번 또는 4번 노드의 자식이다. 5번 노드는 1번 노드에서 방문 될 수 없다.

www.acmicpc.net

이번에는 방문 순서가 아닌 depth를 출력해야 한다. depth는 현재 방문 정점의 depth + 1으로 계산이 가능하다

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<cstring>
#include <string>
#include <math.h>

using namespace std;

vector<int> adj[100001];
int visited[100001];
int visCount = 0;



int main() {
    ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

    int N, M, R; cin >> N >> M >> R;

    fill(&visited[0], &visited[100001], -1);


    for (int i = 0; i < M; i++) {
        int a, b;
        cin >> a >> b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    
    for (int i = 0; i <= N; i++) {
        sort(adj[i].begin(), adj[i].end());
    }

    queue<int> q;
    q.push(R);
    visited[R] = visCount;

    while (!q.empty()) {
        int curr = q.front(); q.pop();

        for (auto now : adj[curr]) {
            if (visited[now] != -1)continue;
            visited[now] = visited[curr] + 1;
            q.push(now);
        }

    }

    if (N < 100)cout << "123123";

    for (int i = 1; i <= N; i++) {
        cout << visited[i]<<'\n';
    }

}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/01   »
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
글 보관함