위상정렬의 개념을 알고 문제에 접근하는 방법이 좋다고 생각됩니다~
간단하게 위상정렬을 설명하면 트리의 방향이 무조건 정해져있다고 생각하시면 됩니다.
(게임으로 설명을하면 빌드 또는 테크라 생각하시쉬면 쉽습니다.)
(A건물을 지어야만 B건물을 지을 수 있다! or A아이템의 상위템이 B아이템이다.)
![]()
만약, 문제의 조건중에 순환할 수 있다는 말이 있다면 위상정렬로 풀 수 없습니다.
(순환한다는 말은 A건물의 상위건물이 B이고, B건물의 상위건물이 A라면 말이 모순이 있겠죠?)
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <math.h>
#include <queue>
#include <utility>
#include <functional>
#define MAX 40005
#define MOD 1000000007
#pragma warning(disable:4996)
using namespace std;
int n, m,a,b,node[32005];
vector<int> vert[32005];
priority_queue<nt,vector<int>,greater<int>> pq;
int main()
{
fill_n(&node[0], 32005, 0);
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++)
{
scanf("%d %d", &a, &b);
vert[a].push_back(b);
node[b]++;
}
for (int i = 1; i <= n; i++)
if (node[i] == 0)
pq.push(i);
while (!pq.empty())
{
int cur = pq.top();
pq.pop();
while (!vert[cur].empty())
{
int tmp = vert[cur].back();
vert[cur].pop_back();
node[tmp]--;
if (node[tmp] == 0)
pq.push(tmp);
}
printf("%d ", cur);
}
return 0;
}
'IT > BOJ' 카테고리의 다른 글
| 백준(BOJ) 11779 최소비용 구하기 2 ** (0) | 2018.06.01 |
|---|---|
| 백준(BOJ) 1261 알고스팟 2 ** (0) | 2018.06.01 |
| 백준(BOJ) 2623 음악프로그램 *** (0) | 2018.06.01 |
| 백준(BOJ) 1938 통나무 ** (0) | 2018.05.31 |
| 백준(BOJ) 2468 안전 영역 ** (0) | 2018.05.31 |