Cod sursa(job #2925511)

Utilizator raresgherasaRares Gherasa raresgherasa Data 15 octombrie 2022 15:14:01
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>

using namespace std;

const string fisier = "ctc";

ifstream fin (fisier + ".in");
ofstream fout (fisier + ".out");

const int NM = 1e5 + 5;

set<int>s[NM];
int x[NM], y[NM], used[NM];
vector<int>g[NM], newg[NM], stk;
int n, m, cnt;

void dfs (int nod){
  used[nod] = true;
  for (int u : g[nod]){
    if (!used[u]){
      dfs(u);
    }
  }
  stk.push_back(nod);
}

void newdfs (int nod){
  used[nod] = true;
  s[cnt].insert(nod);
  for (int u : newg[nod]){
    if (!used[u]){
      newdfs(u);
    }
  }
}

void kosa(){
  for (int i = 1; i <= n; i++){
    if (!used[i]){
      dfs(i);
    }
  }
  memset(used, 0, sizeof(used));
  for (int i = n - 1; i >= 0; i--){
    if (!used[stk[i]]){
      newdfs(stk[i]);
      cnt += 1;
    }
  }
  fout << cnt << '\n';
  for (int i = 0; i < cnt; i++){
    for (int x : s[i]){
      fout << x << " ";
    }
    fout << '\n';
  }
}

int main(){
  fin >> n >> m;
  for (int i = 0; i < m; i++){
    fin >> x[i] >> y[i];
    g[x[i]].push_back(y[i]);
    newg[y[i]].push_back(x[i]);
  }
  kosa();
}