Cod sursa(job #2928200)

Utilizator teochess2017Togan Teodor-Bogdan teochess2017 Data 22 octombrie 2022 13:47:43
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;

#define MAXN 100000

struct ctc{
  int index, lowlink;
  bool onstiva;
};

ctc noduri[MAXN];
vector <int> graf[MAXN];
vector <int> comp[MAXN];
vector <int> stiva;

void findcomponents(int node, int &index, int &nrc){
  int i;
  noduri[node] = {index, index, true};
  index++;
  stiva.push_back(node);
  for(i = 0; i < graf[node].size(); i++){
    if(noduri[graf[node][i]].index == 0){
      findcomponents(graf[node][i], index, nrc);
      if(noduri[graf[node][i]].lowlink < noduri[node].lowlink){
        noduri[node].lowlink = noduri[graf[node][i]].lowlink;
      }
    }else if(noduri[graf[node][i]].onstiva == true){
      if(noduri[graf[node][i]].lowlink < noduri[node].lowlink){///dfhdsfbdshfbsbdjfjkasdhbfhdj
        noduri[node].lowlink = noduri[graf[node][i]].lowlink;
      }
    }
  }
  if(noduri[node].lowlink == noduri[node].index){
    while(stiva[stiva.size() - 1] != node){
      comp[nrc].push_back(stiva[stiva.size() - 1]);
      noduri[stiva[stiva.size() - 1]].onstiva = false;
      stiva.pop_back();
    }
    comp[nrc].push_back(stiva[stiva.size() - 1]);
    noduri[stiva[stiva.size() - 1]].onstiva = false;
    stiva.pop_back();
    nrc++;
  }
}

int main()
{
    FILE *fin, *fout;
    int n, m, i, a, b, nrc, index, j;
    fin = fopen("ctc.in", "r");
    fscanf(fin, "%d%d", &n, &m);
    for(i = 0; i < m; i++){
      fscanf(fin, "%d%d", &a, &b);
      graf[a - 1].push_back(b - 1);
    }
    fclose(fin);
    nrc = 0;
    index = 1;
    for(i = 0; i < n; i++){
      if(noduri[i].index == 0){
        findcomponents(i, index, nrc);
      }
    }
    fout = fopen("ctc.out", "w");
    fprintf(fout, "%d\n", nrc);
    for(i = 0; i < nrc; i++){
      for(j = 0; j < comp[i].size(); j++){
        fprintf(fout, "%d ", comp[i][j] + 1);
      }
      fprintf(fout, "\n");
    }
    fclose(fout);
    return 0;
}