Cod sursa(job #2971504)

Utilizator samyro14Samy Dragos samyro14 Data 27 ianuarie 2023 15:08:44
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

#define ll unsigned long long
#define fast_read ios :: sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
const int maxn = 1e5;
const int mod = 1e6 + 7;

int n, m;
vector<int> a[maxn + 2], b[maxn + 2];
vector<int> c;
vector<int> ctc[maxn + 2];
bitset<maxn + 2> visited;
int k;
void read(){
  fin >> n >> m;
  for(int i = 1; i <= m; ++i){
    int x, y;
    fin >> x >> y;
    a[x].push_back(y);
    b[y].push_back(x);
  }
}
void dfs1(int i){
  visited[i] = 1;
  for(auto x : a[i])
    if(!visited[x])
      dfs1(x);
  c.push_back(i);
}
void dfs2(int i){
  visited[i] = 1;
  ctc[k].push_back(i);
  for(auto x : b[i])
    if(!visited[x])
      dfs2(x);
}
int main(){
  read();   
  for(int i = 1; i <= n; ++i)
    if(!visited[i])
      dfs1(i);
  for(int i = 1; i <= n; ++i)
      visited[i] = 0;
  reverse(c.begin(), c.end());
  for(auto x : c){
    if(!visited[x]){
      k++;
      dfs2(x);
    }
  }
  fout << k << "\n";
  for(int i = 1; i <= k; ++i, fout << '\n')
    for(auto x : ctc[i])
      fout << x << " ";
  return 0;
}
/*

*/