Advertisement
coloriot

22_3

Sep 6th, 2024
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. class Stack {
  7. private:
  8.     vector<int> data;
  9.  
  10. public:
  11.     void push(int value) {
  12.         data.push_back(value);
  13.     }
  14.  
  15.     void pop() {
  16.         if (!data.empty()) {
  17.             data.pop_back();
  18.         }
  19.     }
  20.  
  21.     int top() {
  22.         if (!data.empty()) {
  23.             return data.back();
  24.         }
  25.         return -1;
  26.     }
  27.  
  28.     bool isEmpty() {
  29.         return data.empty();
  30.     }
  31. };
  32.  
  33. class Cycle {
  34. public:
  35.     int start;
  36.     int finish;
  37.  
  38.     Cycle(int s, int f) {
  39.         start = s;
  40.         finish = f;
  41.     }
  42. };
  43.  
  44. class Graph {
  45. private:
  46.     vector<Cycle> cycles;
  47.     vector<bool> visited;
  48.  
  49.     // Поиск в глубину - ищет и считает циклы
  50.     void dfs(int node, int& cycleCount) {
  51.         visited[node] = true;
  52.         int next = cycles[node].finish - 1;
  53.         if (!visited[next]) {
  54.             dfs(next, cycleCount);
  55.         } else {
  56.             cycleCount++;
  57.         }
  58.     }
  59.  
  60. public:
  61.     Graph(int N) {
  62.         visited.resize(N, false);
  63.     }
  64.  
  65.     ~Graph() {
  66.     }
  67.     void addCycle(int start, int finish) {
  68.         Cycle newCycle(start, finish);
  69.         cycles.push_back(newCycle);
  70.     }
  71.  
  72.     int countDisjointCycles() {
  73.         int cycleCount = 0;
  74.         for (int i = 0; i < cycles.size(); ++i) {
  75.             if (!visited[i]) {
  76.                 dfs(i, cycleCount);
  77.             }
  78.         }
  79.         return cycleCount;
  80.     }
  81. };
  82.  
  83. int main() {
  84.     int N;
  85.     cout << "Число: ";
  86.     cin >> N;
  87.     Graph graph(N);
  88.  
  89.     cout << "Старт и начало: " << endl;
  90.     for (int i = 0; i < N; ++i) {
  91.         int start, finish;
  92.         cin >> start >> finish;
  93.         graph.addCycle(start, finish);
  94.     }
  95.     cout << "Число непересекающихся" << graph.countDisjointCycles() << endl;
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement