Pagini recente » Cod sursa (job #1190602) | Cod sursa (job #914603) | Cod sursa (job #509389) | Cod sursa (job #1624335) | Cod sursa (job #1070270)
#include <fstream>
#include <sstream>
#include <deque>
using namespace std;
//int e_026_componente_tare_conexe()
int main()
{
string in_file = "ctc.in";
string out_file = "ctc.out";
int N, M;
const int MAX_N = 5000;
//the adjacency list and the transpose adjacency list
deque<int> adj[MAX_N + 1], adjT[MAX_N + 1];
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);
adjT[v2].push_back(v1);
}
ifs.close();
//plus-minus paradigm
int components_map[MAX_N + 1];
char plus[MAX_N + 1]; //plus (1) or minus (0) or none (-1)
char minus[MAX_N + 1];
for (int v = 1; v <= N; v++) components_map[v] = plus[v] = minus[v] = 0;
int component_id = 0;
for (int v = 1; v <= N; v++)
{
//check if the current node belongs to a component
if (components_map[v] == 0) { //if not assigned
//perform a plus-minus node identification
component_id++;
components_map[v] = component_id; //assign the node to a distinct component
//search the connex component subgraph of the current node v
//breadth search the grapsh starting with the current node v and mark the parsed nodes with +
//initialize the plus-minus status of the nodes
for (int i = 1; i <= N; i++) plus[i] = minus[i] = 0;
deque<int> Q;
Q.push_back(v); plus[v] = 1;
while (!Q.empty()) {
int v1 = Q.front();
Q.pop_front();
//parse the adjacency list of the node v1
for (deque<int>::iterator it = adj[v1].begin(); it != adj[v1].end(); it++) {
int v2 = *it;
if (plus[v2] == 0) {
Q.push_back(v2);
plus[v2] = 1;
}
}
}
//breadth search the transpose graph starting with the current node v and mark the parsed nodes with -
Q.push_back(v); minus[v] = 1;
while (!Q.empty()) {
int v1 = Q.front();
Q.pop_front();
//parse the adjacency list of the node v1
for (deque<int>::iterator it = adjT[v1].begin(); it != adjT[v1].end(); it++) {
int v2 = *it;
if (minus[v2] == 0) {
Q.push_back(v2);
minus[v2] = 1;
}
}
}
//find the +- nodes
for (int i = 1; i <= N; i++) {
if (plus[i] && minus[i]) components_map[i] = component_id;
}
}
}
int no_of_components = component_id;
stringstream* ss = new stringstream[no_of_components + 1];
for (int v = 1; v <= N; v++) {
int c = components_map[v];
ss[c] << v << " ";
}
ofstream ofs(out_file);
ofs << no_of_components << endl;
for (int c = 1; c <= no_of_components; c++) ofs << ss[c].str() << endl;
ofs.close();
//release the memory
delete[] ss;
return 0;
}