Cod sursa(job #3226967)

Utilizator Asgari_ArminArmin Asgari Asgari_Armin Data 23 aprilie 2024 15:23:37
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1e5;

vector <int> g[NMAX + 2];
int vizTime[NMAX + 2];
int highestNode[NMAX + 2];
int onStack[NMAX + 2];
int stackNode[NMAX + 2];

int stackIndex;
int nrComp;
int currTime;

void resetValues(int n) {
  for (int i = 1; i <= n; ++i)
    highestNode[i] = vizTime[i] = onStack[i] = 0;
  currTime = 0;
  stackIndex = 0;
}



void dfs(int node, int parent, int print) {
  highestNode[node] = node;
  vizTime[node] = ++currTime;
  stackNode[++stackIndex] = node;
  onStack[node] = 1;

  for (int newNode : g[node]) {
    if (!vizTime[newNode]) {
      dfs(newNode, node, print);
      if (vizTime[highestNode[newNode]] < vizTime[highestNode[node]])
        highestNode[node] = highestNode[newNode];
    }
    else if (onStack[newNode]){
        if (vizTime[highestNode[newNode]] < vizTime[highestNode[node]])
          highestNode[node] = highestNode[newNode];
    }
  }

  if (highestNode[node] == node) {
    ++nrComp;
    while (stackNode[stackIndex] != node) {
      if (print > 0)
        fout << stackNode[stackIndex] << " ";
      onStack[stackNode[stackIndex]] = 0;
      --stackIndex;
    }
    if (print > 0) {
      fout << node << "\n";
    }
    onStack[node] = 0;
    --stackIndex;
  }
}

int main() {
  int n, m;

  fin >> n >> m;

  for (int i = 1; i <= m; ++i) {
    int x, y;
    fin >> x >> y;
    g[x].push_back(y);
  }
  for (int i = 1; i <= n; ++i) {
    if (!vizTime[i])
      dfs(i, 0, 0);
  }
  fout << nrComp << "\n";

  resetValues(n);
  for (int i = 1; i <= n; ++i) {
    if (!vizTime[i])
      dfs(i, 0, 1);
  }
  return 0;
}