Pagini recente » Istoria paginii runda/fjj | Istoria paginii runda/oji-2008-11-12 | Cod sursa (job #1278458) | Atasamentele paginii Rezultate Zaharel | Cod sursa (job #2798173)
#include <vector>
#include <fstream>
#include <stack>
#include <queue>
#include <iostream>
using namespace std;
ifstream f("ctc.in");
ofstream o("ctc.out");
class Graph
{
public:
vector<vector<int>> adjList;
int size;
Graph(int n)
{
size = n;
adjList.resize(size);
}
void addEdge(int start, int end)
{
adjList[start].push_back(end);
}
void DFS1(int node, vector<bool>& vis, stack<int>& S)
{
vis[node] = true;
for (auto i : adjList[node])
if (!vis[i])
DFS1(i, vis, S);
S.push(node);
}
void DFS2(int node, vector<bool>& vis,vector<vector<int>> &scc,int it)
{
vis[node] = true;
//o << node + 1 << " ";
scc[it].push_back(node);
for (auto i : adjList[node])
if (!vis[i])
DFS2(i, vis,scc,it);
}
Graph TransposeGraph()
{
Graph Tg(size);
for (int i = 0; i < size; i++)
for (auto j: adjList[i])
Tg.adjList[j].push_back(i);
return Tg;
}
void SCC()
{
int it=0;
int k=0;
vector<vector<int>> scc;
stack<int> S;
vector<bool> vis;
for (int i = 0; i < size; i++)
vis.push_back(false);
for (int i = 0; i < size; i++)
if (!vis[i])
DFS1(i, vis, S);
Graph Tg = TransposeGraph();
for (int i = 0; i < size; i++)
vis[i] = false;
while (!S.empty())
{
int node = S.top();
S.pop();
if (!vis[node])
{
scc.resize(it+1);
Tg.DFS2(node, vis,scc,it);
k++;
it++;
}
}
o<<it<<endl;
for(int i=0;i<scc.size();i++)
{
for(int j=0;j<scc[i].size();j++)
o<<scc[i][j]+1<<" ";
o<<endl;
}
}
};
int main()
{
int n, m;
int x, y;
f >> n >> m;
Graph g(n);
for (int i = 1; i <= m; i++)
{
f >> x >> y;
g.addEdge(x - 1, y - 1);
}
g.SCC();
return 0;
}