Cod sursa(job #3284994)

Utilizator KRISTY06Mateiu Ianis Cristian Vasile KRISTY06 Data 12 martie 2025 13:45:43
Problema Componente tare conexe Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("ctc.in");
ofstream fout("ctc.out");

vector<int> graph[100001];
vector<int> ans[100001];

int tree[400001];

bitset<100001> stronglyCompFound;
bitset<100001> isVisited;
bitset<100001> isRootVisited;

int findRoot(int startNode) {
    int root = startNode;
    while (tree[root]) {
        root = tree[root];
    }
    int currentNode = startNode;
    while (tree[currentNode]) {
        int aux = currentNode;
        currentNode = tree[currentNode];
        tree[aux] = root;
    }
    return root;
}

void dfs(int currentNode, vector<int> nodes) {
    isVisited[currentNode] = 1;
    for (vector<int>::iterator it = graph[currentNode].begin(); it != graph[currentNode].end(); ++it) {
        if (isVisited[*it] == 0) {
            nodes.push_back(*it);
            dfs(*it, nodes);
            nodes.pop_back();
        } else {
            for (vector<int>::iterator it2 = find(nodes.begin(), nodes.end(), *it); it2 != nodes.end(); ++it2) {
                if (findRoot(*it2) != findRoot(*it)) {
                    stronglyCompFound[*it2] = stronglyCompFound[*it] = 1;
                    tree[findRoot(*it2)] = findRoot(*it);
                }
            }
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int node1, node2;
        fin >> node1 >> node2;
        graph[node1].push_back(node2);
    }
    for (int i = 1; i <= n; ++i) {
        if (stronglyCompFound[i] == 0) {
            isVisited &= 0;
            dfs(i, {i});
        }
    }
    int ansLen = 0;
    for (int i = 1; i <= n; ++i) {
        ans[findRoot(i)].push_back(i);
        if (isRootVisited[findRoot(i)] == 0) {
            isRootVisited[findRoot(i)] = 1;
            ++ansLen;
        }
    }
    fout << ansLen << '\n';
    for (int i = 1; i <= n; ++i) {
        for (int j = 0; j < ans[i].size(); ++j) {
            fout << ans[i][j] << ' ';
        }
        if (!ans[i].empty()) {
            fout << '\n';
        }
    }
    return 0;
}
/*



 */