Pagini recente » Istoria paginii utilizator/mirunagroza | Cod sursa (job #1737397) | Cod sursa (job #973341) | Rating Luca Robert (robertluca) | Cod sursa (job #1070568)
#include <fstream>
#include <sstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
namespace e_026_ctc_gabow{
const int MAX_N = 100000;
int N;
int index[MAX_N + 1];
int current_index = 0;
vector<int> adj[MAX_N + 1];
int connected_components[MAX_N + 1];
int component_id = 0;
stack<int> S, P;
void gabow(int v)
{
index[v] = ++current_index; //assign a new index to the node; mark the node as read
S.push(v); P.push(v);
//parse the adjacency list of the node
for (vector<int>::iterator it = adj[v].begin(); it != adj[v].end(); it++) {
int w = *it;
//check if w does not have an index or it is already indexed and is in the queue
if (index[w] == 0) gabow(w);
else if (connected_components[w] == 0) { //if not assigned to a strongly connected component
//pop the elements of P until the index of top is lower or equal than the index of the node w
int u;
while (index[u = P.top()] > index[w]) P.pop();
}
}
//if v is the top of P => v is the root of a strongly connected component
if (v == P.top())
{
component_id++;
//pop elements of S until v
int u;
do {
u = S.top(); S.pop();
connected_components[u] = component_id;
} while (u != v);
//remove v from P
P.pop();
}
}
}
//int e_026_componente_tare_conexe_gabow()
int main()
{
using namespace e_026_ctc_gabow;
string in_file = "ctc.in";
string out_file = "ctc.out";
int M;
ifstream ifs(in_file);
ifs >> N >> M;
for (int k = 1; k <= M; k++)
{
int v1, v2;
ifs >> v1 >> v2;
adj[v1].push_back(v2);
}
ifs.close();
for (int v = 1; v <= N; v++) { index[v] = 0; connected_components[v] = 0; }
for (int v = 1; v <= N; v++) if (index[v] == 0) gabow(v);
int no_of_components = component_id;
//stringstream* ss = new stringstream[no_of_components + 1];
//for (int v = 1; v <= N; v++) ss[connected_components[v]] << v << ' ';
ofstream ofs(out_file);
ofs << no_of_components << endl;
//for (int c = 1; c <= no_of_components; c++) ofs << ss[c].str() << '\n';
ofs.close();
//release the memory
//delete[] ss;
return 0;
}