Alex_tz307

CTC lexicografic

Sep 11th, 2020
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define nmax 131072
  3.  
  4. using namespace std;
  5.  
  6. int N, M, x, y, viz[nmax], nr;
  7. vector < int > G[nmax], GT[nmax], CTC[nmax];
  8. stack < int > S;
  9. vector < pair < int , int > > P;
  10.  
  11. void Read () {
  12.     cin >> N >> M;
  13.     while (M --) {
  14.         cin >> x >> y;
  15.         G[x].emplace_back (y);
  16.         GT[y].emplace_back (x);
  17.     }
  18. }
  19.  
  20. void DFSP (int nod) {
  21.     viz[nod] = 1;
  22.     for (size_t i = 0; i < G[nod].size(); ++i)
  23.     if (!viz[G[nod][i]]) DFSP (G[nod][i]);
  24.     S.push (nod);
  25. }
  26.  
  27. void DFSM (int nod) {
  28.     viz[nod] = 2;
  29.     CTC[nr].emplace_back (nod);
  30.     for (size_t i = 0; i < GT[nod].size(); ++i)
  31.     if (viz[GT[nod][i]] == 1) DFSM (GT[nod][i]);
  32. }
  33.  
  34. bool fcmp (pair < int , int > a, pair < int , int > b) {
  35.     return a.second < b.second;
  36. }
  37.  
  38. void Solve () {
  39.     for (int i = 1; i <= N; ++i) if (!viz[i]) DFSP (i);
  40.     while (!S.empty()) {
  41.         int nod = S.top ();
  42.         S.pop ();
  43.         if (viz[nod] == 1) {
  44.             nr ++;
  45.             DFSM (nod);
  46.         }
  47.     }
  48.     for (int i = 1; i <= nr; ++i) {
  49.         sort (CTC[i].begin(), CTC[i].end());
  50.         P.push_back ({i, CTC[i][0]});
  51.     }
  52.     sort (P.begin(), P.end(), fcmp);
  53.     for (int i = 0; i < nr; ++i, cout << '\n')
  54.     for (size_t j = 0; j < CTC[P[i].first].size(); ++j)
  55.     cout << CTC[P[i].first][j] << " ";
  56. }
  57.  
  58. void Boost () {
  59.     ios::sync_with_stdio(false);
  60.     cin.tie (0);
  61.     cout.tie (0);
  62. }
  63.  
  64. int main()
  65. {
  66.     Boost ();
  67.     Read ();
  68.     Solve ();
  69.     return 0;
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment