카테고리 없음

[C/C++] 백준 - 14567번 : 선수과목

JWonK 2021. 11. 11. 22:11
728x90
반응형

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

 

14567번: 선수과목 (Prerequisite)

3개의 과목이 있고, 2번 과목을 이수하기 위해서는 1번 과목을 이수해야 하고, 3번 과목을 이수하기 위해서는 2번 과목을 이수해야 한다.

www.acmicpc.net

문제

올해 Z대학 컴퓨터공학부에 새로 입학한 민욱이는 학부에 개설된 모든 전공과목을 듣고 졸업하려는 원대한 목표를 세웠다. 어떤 과목들은 선수과목이 있어 해당되는 모든 과목을 먼저 이수해야만 해당 과목을 이수할 수 있게 되어 있다. 공학인증을 포기할 수 없는 불쌍한 민욱이는 선수과목 조건을 반드시 지켜야만 한다. 민욱이는 선수과목 조건을 지킬 경우 각각의 전공과목을 언제 이수할 수 있는지 궁금해졌다. 계산을 편리하게 하기 위해 아래와 같이 조건을 간소화하여 계산하기로 하였다.

  1. 한 학기에 들을 수 있는 과목 수에는 제한이 없다.
  2. 모든 과목은 매 학기 항상 개설된다.

모든 과목에 대해 각 과목을 이수하려면 최소 몇 학기가 걸리는지 계산하는 프로그램을 작성하여라.

입력

첫 번째 줄에 과목의 수 N(1≤N≤1000)과 선수 조건의 수 M(0≤M≤500000)이 주어진다. 선수과목 조건은 M개의 줄에 걸쳐 한 줄에 정수 A B 형태로 주어진다. A번 과목이 B번 과목의 선수과목이다. A<B인 입력만 주어진다. (1≤A<B≤N)

출력

1번 과목부터 N번 과목까지 차례대로 최소 몇 학기에 이수할 수 있는지를 한 줄에 공백으로 구분하여 출력한다.

 

 

이 문제는 위상 정렬의 기본 문제이다.

선수과목을 이수해야만 다음 과목을 들을 수 있기 때문에 진입차수를 기준으로 정렬을 수행하는 위상정렬을 수행하면 된다. 지금 2학년 2학기 컴퓨터 알고리즘 수업을 듣고 있어서 C언어로 그래프 코드를 작성했다

#include <iostream>
#include <queue>
#include <vector>
#include <stack>
#include <string>
#include <cstring>
#include <sstream>
#include <set>
#include <unordered_set>
#include <map> 
#include <algorithm>
#include <cmath>
#include <ctime>
#define fastio ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#define ENDL cout << endl
#define ll long long
#define ull unsigned long long
#define INF 18549876543
#define Mod 1000000009
#define endl '\n'
#define pil pair<int,int>

using namespace std;

typedef struct GraphNode {
	int dest;
	GraphNode* next;
}GraphNode;

typedef struct Graph {
	GraphNode* adj;
}Graph;

int N, M;
int inDegree[1003];
int answer[1003];

void Init_Graph(Graph* gph, int count) {
	gph->adj = (GraphNode*)malloc(sizeof(GraphNode) * (count + 1));
	for (int i = 1; i <= count; i++) gph->adj[i].next = NULL;
}

void Reset(Graph* gph, int count) {
	for (int i = 1; i <= count; i++) {
		gph->adj[i].next = NULL;
		free(gph->adj[i].next);
	}
}

int AddDirectedLinked(Graph* gph, int src, int dst) {
	GraphNode* Temp = (GraphNode*)malloc(sizeof(GraphNode));
	Temp->dest = dst;
	Temp->next = gph->adj[src].next;
	gph->adj[src].next = Temp;
	return 1;
}

void topology_Sort(Graph* gph) {
	queue<int> q;
	for (int i = 1; i <= N; i++) {
		if (!inDegree[i]) {
			answer[i] = 1;
			q.push(i);
		}
	}

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

		GraphNode* head = gph->adj[y].next;
		while (head) {
			--inDegree[head->dest];
			if (inDegree[head->dest] == 0) {
				q.push(head->dest);
				answer[head->dest] = answer[y] + 1;
			}
			head = head->next;
		}
	}
}

int main() {
	fastio;
	int from, to;
	Graph graph;
	cin >> N >> M;

	Init_Graph(&graph, N);
	while (M--) {
		cin >> from >> to;
		inDegree[to]++;
		AddDirectedLinked(&graph, from, to);
	}

	topology_Sort(&graph);
	for (int node = 1; node <= N; node++)
		cout << answer[node] << " ";
	Reset(&graph, N);

	return 0;
}
728x90
반응형