Advertisement
RaFiN_

Mr. Kitayuta's Technology cf - 506B

Jul 5th, 2020
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. //cf - 506B
  2.  
  3. const int N = 1e5 + 100;
  4.  
  5. vector<int> g_bi[N], g_uni[N];
  6.  
  7. int col[N];
  8. bool cycle_found;
  9. set<int> visited;
  10. int comp = 0;
  11. vector<int> node;
  12. bool find_cycle;
  13. int ache[N];
  14.  
  15. void cycle(int u) {
  16.     if(find_cycle) return;
  17.     col[u] = 1;
  18.     for(int v : g_uni[u]) {
  19.         if(col[v] == 1) {
  20.             find_cycle = true;
  21.             return;
  22.         }
  23.         if(col[v] == 0) cycle(v);
  24.         if(find_cycle) return;
  25.     }
  26.     col[u] = 2;
  27. }
  28.  
  29. int vis[N];
  30.  
  31. void dfs(int u) {
  32.     vis[u] = comp;
  33.     node.push_back(u);
  34.     for(int v : g_bi[u]) {
  35.         if(vis[v]==0) dfs(v);
  36.     }
  37. }
  38.  
  39.  
  40. int main() {
  41.     ios::sync_with_stdio(0);
  42.     cin.tie(0);
  43.     int n, m;
  44.     cin >> n >> m;
  45.     for(int i = 1; i <= m; i++) {
  46.         int u, v;
  47.         cin >> u >> v;
  48.         g_uni[u].push_back(v);
  49.         g_bi[u].push_back(v);
  50.         g_bi[v].push_back(u);
  51.         ache[u] = ache[v] = 1;
  52.     }
  53.     int ans = 0;
  54.     for(int i = 1; i <= n; i++) {
  55.         ans += ache[i];
  56.     }
  57.     for(int i = 1; i <= n; i++) {
  58.         if(ache[i] && vis[i] == 0) {
  59.             comp++;
  60.             node.clear();
  61.             dfs(i);
  62.             ans--;
  63.             find_cycle = false;
  64.             for(int u : node) {
  65.                 if(col[u] == 0 && find_cycle != true) {
  66.                     cycle(u);
  67.                 }
  68.             }
  69.             ans += find_cycle;
  70.         }
  71.     }
  72.     cout << ans;
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement