Advertisement
Mohammad_Dipu_Sultan

print the cycle with nodes' sum smallest.

Oct 15th, 2023
1,437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> adj[111], cycle;
  5. int vis[111], pathvis[111];
  6.  
  7. vector<int> smallestCycle; // To store the smallest cycle found
  8. int smallestSum = INT_MAX; // To track the smallest sum of nodes in a cycle
  9.  
  10. int dfs(int node) {
  11.     vis[node] = 1;
  12.     pathvis[node] = 1;
  13.     cycle.push_back(node);
  14.  
  15.     for (auto it : adj[node]) {
  16.         if (pathvis[it] == 1) {
  17.             int startIndex = 0;
  18.             while (cycle[startIndex] != it) {
  19.                 startIndex++;
  20.             }
  21.  
  22.             int currentSum = 0;
  23.             vector<int> currentCycle;
  24.  
  25.             // Calculate the sum of nodes and create a vector for the current cycle
  26.             for (int i = startIndex; i < cycle.size(); i++) {
  27.                 currentSum += cycle[i];
  28.                 currentCycle.push_back(cycle[i]);
  29.             }
  30.  
  31.             if (currentSum < smallestSum || (currentSum == smallestSum && currentCycle < smallestCycle)) {
  32.                 smallestSum = currentSum;
  33.                 smallestCycle = currentCycle;
  34.             }
  35.         } else if (vis[it] == 0) {
  36.             if (dfs(it) == true) {
  37.                 return true;
  38.             }
  39.         }
  40.     }
  41.  
  42.     pathvis[node] = 0;
  43.     cycle.pop_back();
  44.     return false;
  45. }
  46.  
  47. int main() {
  48.     int v, e;
  49.     cin >> v >> e;
  50.     for (int i = 0; i < e; i++) {
  51.         int x, y;
  52.         cin >> x >> y;
  53.         adj[x].push_back(y);
  54.     }
  55.     memset(vis, 0, sizeof(vis));
  56.     memset(pathvis, 0, sizeof(pathvis));
  57.  
  58.     for (int i = 0; i < v; i++) {
  59.         if (vis[i] == 0) {
  60.             dfs(i);
  61.         }
  62.     }
  63.  
  64.     // Sort the nodes of the smallest cycle in ascending order
  65.     sort(smallestCycle.begin(), smallestCycle.end());
  66.  
  67.     // Print the smallest cycle
  68.     for (int node : smallestCycle) {
  69.         cout << node << " ";
  70.     }
  71.     cout << endl;
  72.  
  73.     return 0;
  74. }
  75.  
  76. /*5 5
  77. 1 2 2 4 4 5 5 3 3 2
  78.  
  79. 2 3 4 5
  80.  
  81. 5 5
  82. 2 4 2 3 4 3 1 5 5 1
  83.  
  84. 1 5*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement