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

 

2252번: 줄 세우기

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

www.acmicpc.net

이 문제가 Base 이다.

 

 

이하 BFS이다. 많이 써서 익숙하다.

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
52
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#define pii pair<intint>
using namespace std;
 
 
int node[32001= { 0 };
vector<int> edge[32001];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
 
 
    int v, e;
    cin >> v >> e;
    int a, b;
    for (int i = 0; i < e; i++)
    {
        cin >> a >> b;
        edge[a].push_back(b);
        node[b]++;
    }
 
 
    queue<int> q;
    for (int i = 1; i <= v; i++)
    {
        if (node[i] == 0)
            q.push(i);
    }
 
    // if q.empty() => Cycle
    while (!q.empty())
    {
        int t = q.front();
        cout << t << ' ';
        q.pop();
 
        for (int i = 0; i < edge[t].size(); i++)
        {
            int n = edge[t][i];
            node[n]--;
            if (node[n] == 0)
                q.push(n);
        }
    }
}
 
 
cs

 

 

 

 

다음은 DFS이다.

 

 

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
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#define pii pair<intint>
using namespace std;
 
 
bool n_visit[32001= {false};
//bool finish[32001] = {false} 싸이클 판별
int ans[32001];
int ac = 0;
vector<int> edge[32001];
 
void dfs(int node)
{
    n_visit[node] = true;
    for (int i = 0; i < edge[node].size(); i++)
    {
        if (n_visit[edge[node][i]] == false)
            dfs(edge[node][i]);
        //if(finish[edge[node][i] == false) 싸이클 판단의 중요 요소이다.
        // this is Cycle
    }
    ans[ac++= node;
    //finish[node] = true;
}
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
 
    int v, e;
    cin >> v >> e;
    int a, b;
    for (int i = 0; i < e; i++)
    {
        cin >> a >> b;
        edge[a].push_back(b);
    }
 
    for (int i = 1; i <= v; i++)
    {
        if (n_visit[i] == false)
            dfs(i);
    }
    for (int i = ac - 1; i >= 0; i--// 뒤집어줘야 한다.
        cout << ans[i] << ' ';
}
cs

'알고리즘 기술' 카테고리의 다른 글

[DP] TSP(외판원 순회)  (0) 2021.04.08
LCA  (0) 2020.08.20
Trie와 동적 Trie  (0) 2020.08.19
KMP  (0) 2020.07.17
ccw  (0) 2020.07.16

+ Recent posts