Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define nmax 131072
- using namespace std;
- int N, M, x, y, viz[nmax], nr;
- vector < int > G[nmax], GT[nmax], CTC[nmax];
- stack < int > S;
- vector < pair < int , int > > P;
- void Read () {
- cin >> N >> M;
- while (M --) {
- cin >> x >> y;
- G[x].emplace_back (y);
- GT[y].emplace_back (x);
- }
- }
- void DFSP (int nod) {
- viz[nod] = 1;
- for (size_t i = 0; i < G[nod].size(); ++i)
- if (!viz[G[nod][i]]) DFSP (G[nod][i]);
- S.push (nod);
- }
- void DFSM (int nod) {
- viz[nod] = 2;
- CTC[nr].emplace_back (nod);
- for (size_t i = 0; i < GT[nod].size(); ++i)
- if (viz[GT[nod][i]] == 1) DFSM (GT[nod][i]);
- }
- bool fcmp (pair < int , int > a, pair < int , int > b) {
- return a.second < b.second;
- }
- void Solve () {
- for (int i = 1; i <= N; ++i) if (!viz[i]) DFSP (i);
- while (!S.empty()) {
- int nod = S.top ();
- S.pop ();
- if (viz[nod] == 1) {
- nr ++;
- DFSM (nod);
- }
- }
- for (int i = 1; i <= nr; ++i) {
- sort (CTC[i].begin(), CTC[i].end());
- P.push_back ({i, CTC[i][0]});
- }
- sort (P.begin(), P.end(), fcmp);
- for (int i = 0; i < nr; ++i, cout << '\n')
- for (size_t j = 0; j < CTC[P[i].first].size(); ++j)
- cout << CTC[P[i].first][j] << " ";
- }
- void Boost () {
- ios::sync_with_stdio(false);
- cin.tie (0);
- cout.tie (0);
- }
- int main()
- {
- Boost ();
- Read ();
- Solve ();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment