줄 세우기 C++ - 백준 2252

김관중·2024년 3월 11일
0

백준

목록 보기
83/129

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

위상정렬 문제.

문제 접근

위상정렬 해주고 bfs를 돌려주면 된다.

코드는 다음과 같다.

#include <bits/stdc++.h>
using namespace std;

int n,m,A,B;
vector<int> graph[32001];
int cnt[32001]={0,};
queue<int> q;

void solve(){
    while(!q.empty()){
        int now=q.front();
        cout << now << ' ';
        q.pop();
        for(int i=0;i<graph[now].size();i++){
            cnt[graph[now][i]]--;
            if(cnt[graph[now][i]]==0) q.push(graph[now][i]);
        }
    }
}

int main(){
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
    cin >> n >> m;
    for(int i=0;i<m;i++){
        cin >> A >> B;
        graph[A].push_back(B);
        cnt[B]++;
    }
    for(int i=1;i<=n;i++) if(cnt[i]==0) q.push(i);
    solve();
    return 0;
}
profile
꾸준히 학습하기

0개의 댓글

관련 채용 정보