Advertisement
Guest User

Untitled

a guest
Nov 16th, 2019
4,414
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. const int borne = 201*1000;
  7. int nbNodes, nbEdges;
  8.  
  9. vector<int> adj[borne];
  10. bool vu[borne];
  11. vector<pair<int, int>> ivComp;
  12.  
  13. void dfs(int nod, int& weaker, int& bigger)
  14. {
  15.     vu[nod] = true;
  16.     weaker = min(weaker, nod);
  17.     bigger = max(bigger, nod);
  18.  
  19.     for (int neighbor : adj[nod]) if (! vu[neighbor]) {
  20.         dfs(neighbor, weaker, bigger);
  21.     }
  22. }
  23.  
  24. int main()
  25. {
  26.     ios::sync_with_stdio(false);
  27.     cin.tie(0);
  28.  
  29.     cin >> nbNodes >> nbEdges;
  30.     for (int iEdge = 0; iEdge < nbEdges; ++iEdge) {
  31.         int u, v;
  32.         cin >> u >> v;
  33.         --u; --v;
  34.         adj[u].push_back(v);
  35.         adj[v].push_back(u);
  36.     }
  37.  
  38.     for (int nod = 0; nod < nbNodes; ++nod) {
  39.         if (! vu[nod]) {
  40.             int weaker = nod, bigger = nod;
  41.             dfs(nod, weaker, bigger);
  42.             ivComp.emplace_back(weaker, bigger);
  43.         }
  44.     }
  45.  
  46.     //sort(ivComp.begin(), ivComp.end()); // Useless, already sorted
  47.  
  48.     int curEnd = -1;
  49.     int rep = 0;
  50.  
  51.     for (auto comp : ivComp) {
  52.         if (comp.first <= curEnd) {
  53.             ++rep;
  54.         }
  55.         curEnd = max(curEnd, comp.second);
  56.     }
  57.  
  58.     cout << rep << "\n";
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement