Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
Archives
Today
Total
관리 메뉴

hwooo

BOJ (C/C++) 24444번: 알고리즘 수업 - 너비 우선 탐색 1 본문

Study/Algorithm

BOJ (C/C++) 24444번: 알고리즘 수업 - 너비 우선 탐색 1

hwooo 2022. 12. 12. 07:04

https://www.acmicpc.net/problem/24444

 

24444번: 알고리즘 수업 - 너비 우선 탐색 1

첫째 줄에 정점의 수 N (5 ≤ N ≤ 100,000), 간선의 수 M (1 ≤ M ≤ 200,000), 시작 정점 R (1 ≤ R ≤ N)이 주어진다. 다음 M개 줄에 간선 정보 u v가 주어지며 정점 u와 정점 v의 가중치 1인 양방

www.acmicpc.net


풀이

입력 받은 후 각 노드를 오름차순으로 정렬한 후 BFS를 실행하였다. 방문한 기록이 없는 노드만 큐에 저장하고, cnt를 전역변수로 지정하여 큐에 노드를 삽입할 때마다 cnt를 하나씩 증가시키며 방문 순서를 저장하였다.


코드

#include <stdio.h>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

vector <int> V[100001];
int visited[100001];
int N, M, R, cnt = 1;

void BFS(int R) {
	int now;
	queue <int> Q;

	// init
	visited[R] = cnt;
	Q.push(R);

	while (!Q.empty()) {
		now = Q.front();
		Q.pop();

		for (int i : V[now]) {
			if (!visited[i]) {
				Q.push(i);
				visited[i] = ++cnt;
			}
		}
	}
	
}

int main() {
	int a, b;

	// input
	scanf("%d %d %d", &N, &M, &R);
	for (int i = 0; i < M; i++) {
		scanf("%d %d", &a, &b);
		V[a].push_back(b);
		V[b].push_back(a);
	}

	// 오름차순 정렬
	for (int i = 1; i <= N; i++) {
		if (V[i].size() > 1)
			sort(V[i].begin(), V[i].end());
	}

	BFS(R);

	// print
	for (int i = 1; i <= N; i++) printf("%d\n", visited[i]);

	return 0;
}