본문 바로가기
Computer Science

프양연 줄 세우기 / 위상정렬

by OKOK 2018. 12. 24.

1. 위상정렬 구하는 방법

2. DFS, 큐, 디그리 사용 할 수 있음 

3. 그 중에서 익숙한 것 사용하면 됨


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
53
54
55
56
57
58
#include <stdio.h>
 
struct NODE
{
    int n;
    NODE* next;
};
 
const int MAXN = 6, MAXM = 6;
//const int MAXN = 50000, MAXM = 150000;
 
NODE* list[MAXN + 1];
NODE nPool[MAXM];
int CHK[MAXN + 1];
int QUEUE[MAXN];
int wp, rp;
int tc, T, N, M, a, b, s;
 
void process(void)
{
    wp = 0, rp = 0;
    for (int i = 1; i <= N; ++i)
    {
        if (CHK[i] == 0) QUEUE[wp++= i;
    }
 
    while (rp < wp)
    {
        s = QUEUE[rp++];
        for (NODE* n = list[s]; n != NULL; n = n->next)
        {
            if (--CHK[n->n] == 0) QUEUE[wp++= n->n;
        }
    }
}
 
int main(void)
{
    freopen("input.txt""r", stdin);
    for (tc = scanf("%d"&T); tc <= T; ++tc)
    {
        scanf("%d%d"&N, &M);
        for (int i = 0; i < M; ++i)
        {
            scanf("%d%d"&a, &b);
            NODE* n = &nPool[i];
            n->= b, n->next = list[a], list[a] = n;
            ++CHK[b];
        }
        printf("#%d", tc);
        process();
        for (int i = 0; i < wp; ++i) printf(" %d", QUEUE[i]);
        for (int i = 1; i <= N; ++i) CHK[i] = 0, list[i] = NULL;
        puts("");
    }
    return 0;
}
 
cs


댓글