Pagini recente » Cod sursa (job #2292829) | Cod sursa (job #560848) | Cod sursa (job #2201016) | Cod sursa (job #2921173) | Cod sursa (job #2224770)
#include <bits/stdc++.h>
using namespace std;
void dfs(const vector<vector<int>>& graph, int node, vector<bool>& visited, vector<int>& topSort){
visited[node] = true;
for (int x: graph[node])
if (!visited[x])
dfs(graph, x, visited, topSort);
topSort.push_back(node);
}
void dfsT(const vector<vector<int>>& graphT, int node, vector<bool>& visited, vector<int>& comp){
visited[node] = false;
for (int x: graphT[node])
if (visited[x])
dfsT(graphT, x, visited, comp);
comp.push_back(node);
}
int main() {
// ifstream cin("data.txt");
ifstream cin("ctc.in");
ofstream cout("ctc.out");
ios_base::sync_with_stdio(false);
int N, M;
cin >> N >> M;
vector<vector<int>> graph(N);
vector<vector<int>> graphT(N);
while (M--){
int x, y;
cin >> x >> y;
x--; y--;
graph[x].push_back(y);
graphT[y].push_back(x);
}
vector<bool> visited(N, false);
vector<int> topSort;
for (int i = 0; i < N; i++)
if (!visited[i])
dfs(graph, i, visited, topSort);
reverse(topSort.begin(), topSort.end());
vector<vector<int>> comps;
for (int x: topSort)
if (visited[x]) {
comps.push_back({});
dfsT(graphT, x, visited, comps[comps.size() - 1]);
}
cout << comps.size() << "\n";
for (auto x: comps){
for (auto y: x)
cout << y + 1 << " ";
cout << "\n";
}
return 0;
}