Cod sursa(job #3224818)

Utilizator Ruxandra009Ruxandra Vasilescu Ruxandra009 Data 16 aprilie 2024 11:57:51
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

const int nmax = 100005;
int n, m, fr[nmax], p;
vector<int> a[nmax], b[nmax], v[nmax];

void Dfs(int nod)
{
    fr[nod] ++;
    for(int i = 0; i < a[nod].size(); i ++)
    {
        int k = a[nod][i];

        if(fr[k] == 0)
            Dfs(k);
    }
}

void Dfs2(int nod)
{
    fr[nod] ++;
    for(int i = 0; i < b[nod].size(); i ++)
    {
        int k = b[nod][i];

        if(fr[k] == 1)
            Dfs2(k);
    }
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; i ++)
    {
        int x, y;
        f >> x >> y;
        a[x].push_back(y);
        b[y].push_back(x);
    }

    for(int i = 1; i <= n; i ++)
        if(fr[i] == 0)
        {
            Dfs(i);
            Dfs2(i);

            p ++;
            for(int j = 1; j <= n; j ++)
            {
                if(fr[j] == 2)
                {
                    v[p].push_back(j);
                    fr[j] = -1;
                }

                if(fr[j] > 0)
                    fr[j] = 0;
            }
        }

    g << p << '\n';
    for(int i = 1; i <= p; i ++, g << '\n')
        for(int j = 0; j < v[i].size(); j ++)
            g << v[i][j] << " ";
    return 0;
}