본문 바로가기

알고리즘 문제풀이/추천 문제

[ 백준 2552 ] 줄 세우기 (C++)

반응형
 

2252번: 줄 세우기

첫째 줄에 N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)이 주어진다. M은 키를 비교한 회수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의

www.acmicpc.net

 

위상 정렬을 사용하면 간단하게 풀 수 있는 문제다. 위상정렬에 대한 상세한 내용은 알고리즘 파트에서 확인할 수 있다. 링크 바로가기!

 
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

int N, M;
int inDgree[32001] = {0, };
vector<vector<int>> graph(32001);

void topology_sort() {
	queue<int> q;

	for (int i = 1; i <= N; i++) {
		if (inDgree[i] == 0)
			q.push(i); // 진입차수가 0인 노드 push
	}

	for (int rep = 0; rep < N; rep++) {
		if (q.empty()) {
			cout << "비순환 그래프입니다" << endl;
			return;
		}

		int from = q.front();
		cout << from << ' ';
		q.pop();
		for (int i = 0; i < graph[from].size(); i++) {
			int to = graph[from][i];
			inDgree[to]--;
			if (inDgree[to] == 0)
				q.push(to);
		}
	}

}

int main() {
	int a, b;

	cin >> N >> M;
	for (int i = 0; i < M; i++) {
		cin >> a >> b;
		graph[a].push_back(b);
		inDgree[b]++;
	}

	topology_sort();

	return 0;
}
반응형