티스토리 뷰

문제 링크입니다 : https://www.acmicpc.net/problem/2150

 

2150번: Strongly Connected Component

첫째 줄에 두 정수 V(1≤V≤10,000), E(1≤E≤100,000)가 주어진다. 이는 그래프가 V개의 정점과 E개의 간선으로 이루어져 있다는 의미이다. 다음 E개의 줄에는 간선에 대한 정보를 나타내는 두 정수 A, B

www.acmicpc.net

 

강결합 컴포넌트(SCC)  문제이다.

SCC를 해결 하는 알고리즘은 코사라주 알고리즘과 타잔 알고리즘이 있다.

 

코사라주 알고리즘으로 풀었다.

 

 

 

 

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int V, E;
vector<vector<int>> adj;
vector<vector<int>> radj;
vector<bool> visited;

void dfs(int here, vector<int>& rpath) {
    if(visited[here]) return;
    visited[here] = true;

    for(int i = 0; i < adj[here].size(); i++) {
        int next = adj[here][i];
        dfs(next, rpath);
    }
    rpath.push_back(here);
}

void makeSCC(int here, vector<int>& path) {
    if(visited[here]) return;
    visited[here] = true;
    path.push_back(here);

    for(int i = 0; i < radj[here].size(); i++) {
        int next = radj[here][i];
        makeSCC(next, path);
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    cin >> V >> E;
    adj.assign(V + 1, vector<int>());
    radj.assign(V + 1, vector<int>());
    visited.assign(V + 1, false);

    vector<int> path;
    vector<int> rpath;

    int u, v;
    for(int i = 0; i < E; i++) {
        cin >> u >> v;
        adj[u].push_back(v);
        radj[v].push_back(u);
    }

    for(int i = 1; i < radj.size(); i++) {
        dfs(i, rpath);
    }
    
    visited.assign(V + 1, false);

    vector<vector<int>> result;

    for(int i = rpath.size() - 1; i >= 0; i--) {
        int cur = rpath[i];
        makeSCC(cur, path);
        if(!path.empty()) {
            sort(path.begin(), path.end());
            result.push_back(path);
        }
        path.clear();
    }
    cout << result.size() << '\n';
    sort(result.begin(), result.end());
    for(int i = 0; i < result.size(); i++) {
        for(const auto& el : result[i]) {
            cout << el << ' ';
        }
        cout << "-1\n"; 
    }

    return 0;
}

 

 

 

개발 환경 : vscode

지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

 

'알고리즘 > 백준(BOJ)' 카테고리의 다른 글

백준 - 3085 사탕 게임  (0) 2020.07.29
백준 - 2309 일곱 난쟁이  (0) 2020.07.29
백준 - 11437 LCA  (0) 2020.07.23
백준 - 3584 가장 가까운 공통 조상  (0) 2020.07.21
백준 - 1005 ACM Craft  (0) 2020.07.19
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/06   »
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
글 보관함