본문 바로가기

백준 문제 풀이

백준 1766번 문제집 (C++)

728x90

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

 

1766번: 문제집

첫째 줄에 문제의 수 N(1 ≤ N ≤ 32,000)과 먼저 푸는 것이 좋은 문제에 대한 정보의 개수 M(1 ≤ M ≤ 100,000)이 주어진다. 둘째 줄부터 M개의 줄에 걸쳐 두 정수의 순서쌍 A,B가 빈칸을 사이에 두고 주

www.acmicpc.net

위상 정렬문제이다.

줄세우기 문제와 유사하지만 중요한 건 이번에는 이왕이면 더 작은 수 부터 해야하기 때문에 bfs 방식만을 사용해서 우선순위큐를 만들어줘야한다.

 

정답 코드

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

int N, M;
vector<int> graph[32001];
bool check[32001] = { false, };
int degree[32001];

priority_queue<int, vector<int>, greater<int>> pq;

int main() {
	ios_base::sync_with_stdio(NULL);
	cin.tie(NULL);

	cin >> N >> M;

	for (int i = 1; i <= N; i++) {
		degree[i] = 0;
	}

	for (int i = 0; i < M; i++) {
		int a, b;
		cin >> a >> b;

		graph[a].push_back(b);
		degree[b]++;
	}

	for(int i = 1; i <= N; i++)
		if (degree[i] == 0) { pq.push(i); check[i] = true; }
	
	

	while (!pq.empty()) {
		int node = pq.top();
		pq.pop();

		cout << node << " ";

		for (int i = 0; i < graph[node].size(); i++) {
			int now_node = graph[node][i];

			if (check[now_node]) continue;
			
			degree[now_node]--;
			
			if (degree[now_node] == 0) {
				pq.push(now_node);
				check[now_node] = true;
			}
		}
	}
}

 

'백준 문제 풀이' 카테고리의 다른 글

백준 9084번 동전(C++)  (0) 2023.09.09
백준 6593번 상범 빌딩(C++)  (0) 2023.09.07
백준 2252번 줄세우기 (C++)  (0) 2023.08.22
백준 14391번 종이 조각 (C++)  (0) 2023.08.12
백준 1043번 - 거짓말(C++)  (0) 2023.08.08