Pagini recente » Cod sursa (job #1633951) | Razvy | Cod sursa (job #451373) | Cod sursa (job #1291788) | Cod sursa (job #2343564)
#include <vector>
#include <cstring>
#include <fstream>
#include <algorithm>
#define NMAX 100010
using std::vector;
using std::random_shuffle;
std::ifstream fin("ctc.in");
std::ofstream fout("ctc.out");
int n, m;
vector<int> ad1[NMAX];
vector<int> ad2[NMAX];
bool done[NMAX];
bool plus[NMAX];
bool minus[NMAX];
int nrComp;
vector<int> comp[NMAX];
void dfs(vector<int> ad[], bool vis[], int node) {
vis[node] = true;
for (int i = 0; i < (int) ad[node].size(); i++)
if (!vis[ad[node][i]])
dfs(ad, vis, ad[node][i]);
}
void start(int src) {
memset(plus, false, sizeof(plus));
memset(minus, false, sizeof(minus));
dfs(ad1, plus, src);
dfs(ad2, minus, src);
for (int i = 1; i <= n; i++)
if (plus[i] && minus[i]) {
done[i] = true;
comp[nrComp].push_back(i);
}
nrComp++;
}
int main() {
fin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y;
fin >> x >> y;
ad1[x].push_back(y);
ad2[y].push_back(x);
}
int nodes[NMAX];
for (int i = 1; i <= n; i++)
nodes[i] = i;
random_shuffle(nodes + 1, nodes + n + 1);
for (int i = 1; i <= n; i++)
if (!done[nodes[i]])
start(nodes[i]);
fout << nrComp << '\n';
for (int i = 0; i < nrComp; i++) {
for (int j = 0; j < (int) comp[i].size(); j++)
fout << comp[i][j] << ' ';
fout << '\n';
}
fout.close();
return 0;
}