Pagini recente » Rating petru ciur (petruciur) | Cod sursa (job #3127917) | Cod sursa (job #2742329) | Cod sursa (job #2316433) | Cod sursa (job #439982)
Cod sursa(job #439982)
/*
* PA 2010
* Laborator 7 - Aplicatii DFS
*
* Determinarea componentelor tare conexe
*
*/
#include <cstdio> // printf, scanf
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
#define min(a, b) ((a) < (b) ? (a) : (b))
typedef vector<int> *graf_t;
int n, m;
graf_t G; // lista de adiacenta si transpusa
stack<int> S;
vector <vector<int> > sol;
int Index = 0;
int *idx, *lowlink;
bool *onstack;
void read_data(const char *filename)
{
ifstream fin;
int x, y;
fin.open(filename);
fin >> n >> m;
G = new vector<int>[n];
for (int i = 0; i < m; i++) {
fin >> x >> y;
x--; y--; // Indexare de la 0
G[x].push_back(y);
}
}
/* Tarjan */
void tarjan(int v)
{
idx[v] = Index;
lowlink[v] = Index;
Index++;
S.push(v);
onstack[v] = true;
vector<int>::const_iterator i;
for (i = G[v].begin(); i < G[v].end(); i++) {
int u = *i;
if (idx[u] == -1) {
tarjan(u);
lowlink[v] = min(lowlink[v], lowlink[u]);
}
else if (onstack[u])
lowlink[v] = min(lowlink[v], idx[u]);
}
if (lowlink[v] == idx[v]) { // radacina unei CTC
vector<int> temp;
int u;
do {
u = S.top();
S.pop();
onstack[u] = false;
temp.push_back(u);
} while (u != v);
sol.push_back(temp);
}
}
void ctc_tarjan()
{
Index = 0;
idx = new int[n];
lowlink = new int[n];
onstack = new bool[n];
for (int v = 0; v < n; v++) {
idx[v] = -1;
onstack[v] = false;
}
for (int v = 0; v < n; v++)
if (idx[v] == -1)
tarjan(v);
}
void print_sol(const char *filename)
{
ofstream fout;
fout.open(filename);
fout << sol.size() << endl;
vector<vector<int> >::const_iterator i;
for (i = sol.begin(); i < sol.end(); i++) {
vector<int>::const_iterator j;
for (j = (*i).begin(); j < (*i).end(); j++)
fout << *j + 1 << " ";
fout << endl;
}
fout.close();
}
int main()
{
read_data("ctc.in");
ctc_tarjan();
print_sol("ctc.out");
return 0;
}