Algorithm/BOJ
줄 세우기 - 2252
jhg0406
2020. 3. 4. 03:12
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
//2252 - 줄 세우기
#include <iostream>
#include <vector>
using namespace std;
int N, M;
vector<vector<int>> adj;
vector<int> order;
vector<bool> seen;
void init()
{
cin >> N >> M;
adj = vector<vector<int>>(N+1);
seen = vector<bool>(N+1, false);
int u, v;
for(int i = 0; i<M; ++i)
{
cin >> u >> v;
adj[v].push_back(u);
}
}
void dfs(int here)
{
seen[here] = true;
for(int i = 0; i<adj[here].size(); ++i)
{
int there = adj[here][i];
if(!seen[there])
dfs(there);
}
order.push_back(here);
}
void topologicalSort()
{
for(int i = 1; i<=N; ++i)
if(!seen[i])
dfs(i);
for(int i = 0; i<N; ++i)
cout << order[i] << " ";
}
int main()
{
init();
topologicalSort();
}
|
cs |
https://www.acmicpc.net/problem/2252
2252번: 줄 세우기
첫째 줄에 N(1≤N≤32,000), M(1≤M≤100,000)이 주어진다. M은 키를 비교한 회수이다. 다음 M개의 줄에는 키를 비교한 두 학생의 번호 A, B가 주어진다. 이는 학생 A가 학생 B의 앞에 서야 한다는 의미이다. 학생들의 번호는 1번부터 N번이다.
www.acmicpc.net
줄 세우기
위상정렬 문제
DAG가 아닌 입력이 없어 싸이클이 생기는 경우를 골라내는 부분은 넣지 않았습니다.