Cod sursa(job #3036628)

Utilizator pctirziuTirziu Petre pctirziu Data 24 martie 2023 18:31:48
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;
ifstream cin("ctc.in");
ofstream cout("ctc.out");
const int nmax = 2e5 + 5;
int componenta[nmax], grad[nmax], vis[nmax];
vector <int> edge[nmax];
vector <int> revedge[nmax];
stack <int> st;
vector <int> ceva[nmax];
void dfs(int node)
{
    vis[node] = 1;
    for(int i = 0; i < edge[node].size(); i++)
        if(!vis[edge[node][i]])
            dfs(edge[node][i]);
    st.push(node);
}
void dfs1(int node, int cnt)
{
    vis[node] = 1;
    componenta[node] = cnt;
    ceva[cnt].push_back(node);
    for(int i = 0; i < revedge[node].size(); i++)
        if(!vis[revedge[node][i]])
            dfs1(revedge[node][i], cnt);
}
int main()
{
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= m; i++){
        int x, y;
        cin >> x >> y;
        edge[x].push_back(y);
        revedge[y].push_back(x);
    }
    for(int i = 1; i <= n; i++)
        if(!vis[i])
            dfs(i);
    for(int i = 1; i <= n; i++)
        vis[i] = 0;
    int cnt = 0;
    while(!st.empty()){
        int curr = st.top();
        if(!vis[curr])
            dfs1(curr, ++cnt);
        st.pop();
    }
    cout << cnt << "\n";
    for(int i = 1; i <= cnt; i++){
        for(int j = 0; j < ceva[i].size(); j++)
            cout << ceva[i][j] << " ";
        cout << "\n";
    }
    //for(int i = 1; i <= n; i++)
        //cout << componenta[i] << " ";
    return 0;
}