[C/C++] Topology Sort (graph)

2023. 6. 27. 15:11·Computer Science/Algorithm

백준 14567문제

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define PS_INPUT cout.tie(NULL); cin.tie(NULL); ios_base::sync_with_stdio(false)
#define endl '\n'
#define INF 1e9
#define pii pair<int, int>
#define ll long long
#define SIZE 1001

int n, m;
int inDegree[SIZE];
vector<int> graph[SIZE];
int result[SIZE];
queue<int> q;

void initInput() {
    cin >> n >> m;
    int a, b;
    for (int i = 0; i < m; i++) {
        cin >> a >> b;
        graph[a].push_back(b);
        inDegree[b] += 1;
    }
}

void topologySort() {
    for (int i = 1; i <= n; i++) {
        if (!inDegree[i]) {
            q.push(i);
            result[i] = 1;
        }
    }

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

        for (int i = 0; i < graph[cur].size(); i++) {
            int next = graph[cur][i];
            inDegree[next] -= 1;

            if (!inDegree[next]) {
                q.push(next);
                result[next] = result[cur] + 1;
            }
        }
    }
}

void solve() {
    topologySort();
    for (int i = 1; i <= n; i++) cout << result[i] << ' ';
    cout << endl;
}

int main(void)
{
    PS_INPUT; 
    initInput();
    solve();

    return 0;
}
저작자표시 (새창열림)

'Computer Science > Algorithm' 카테고리의 다른 글

[C/C++] kruskal algorithm (MST)  (0) 2023.06.27
[C/C++] prim algorithm (MST)  (0) 2023.06.27
[C/C++] 에라토스테네스의 체  (0) 2023.05.30
[C/C++] BFS(Breadth-First Search)  (0) 2023.05.30
[C/C++] DFS(Depth-First Search)  (0) 2023.05.30
'Computer Science/Algorithm' 카테고리의 다른 글
  • [C/C++] kruskal algorithm (MST)
  • [C/C++] prim algorithm (MST)
  • [C/C++] 에라토스테네스의 체
  • [C/C++] BFS(Breadth-First Search)
Study with Me!
Study with Me!
Study with Me!
  • Study with Me!
    Seongmo
    Study with Me!
  • 전체
    오늘
    어제
    • Computer (147)
      • Computer Science (61)
        • Data Structure (51)
        • Algorithm (6)
        • 선형대수 with C++ (4)
      • Backend (11)
        • 백엔드 취업을 위해.. (1)
        • Spring (10)
        • Database (0)
        • Testing (0)
        • Infra & DevOps (0)
      • Arm Architecture (1)
        • Register (0)
        • Assembly Instruction (1)
      • Linux (32)
        • Linux Kernel (4)
        • 라이브러리 함수 구현하기 (0)
        • 쉘, 쉘 명령어 구현하기 (15)
        • Ubuntu (13)
      • Cloud Infrastructure (8)
        • Kubernetes (7)
        • OpenStack Magnum (1)
      • AWS (3)
      • Baekjoon (18)
      • Tools (6)
        • Git & Github (5)
        • Vim (1)
      • 개발 환경 (7)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    STL
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Study with Me!
[C/C++] Topology Sort (graph)
상단으로

티스토리툴바