Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> adj[111], cycle;
- int vis[111], pathvis[111];
- vector<int> smallestCycle; // To store the smallest cycle found
- int smallestSum = INT_MAX; // To track the smallest sum of nodes in a cycle
- int dfs(int node) {
- vis[node] = 1;
- pathvis[node] = 1;
- cycle.push_back(node);
- for (auto it : adj[node]) {
- if (pathvis[it] == 1) {
- int startIndex = 0;
- while (cycle[startIndex] != it) {
- startIndex++;
- }
- int currentSum = 0;
- vector<int> currentCycle;
- // Calculate the sum of nodes and create a vector for the current cycle
- for (int i = startIndex; i < cycle.size(); i++) {
- currentSum += cycle[i];
- currentCycle.push_back(cycle[i]);
- }
- if (currentSum < smallestSum || (currentSum == smallestSum && currentCycle < smallestCycle)) {
- smallestSum = currentSum;
- smallestCycle = currentCycle;
- }
- } else if (vis[it] == 0) {
- if (dfs(it) == true) {
- return true;
- }
- }
- }
- pathvis[node] = 0;
- cycle.pop_back();
- return false;
- }
- int main() {
- int v, e;
- cin >> v >> e;
- for (int i = 0; i < e; i++) {
- int x, y;
- cin >> x >> y;
- adj[x].push_back(y);
- }
- memset(vis, 0, sizeof(vis));
- memset(pathvis, 0, sizeof(pathvis));
- for (int i = 0; i < v; i++) {
- if (vis[i] == 0) {
- dfs(i);
- }
- }
- // Sort the nodes of the smallest cycle in ascending order
- sort(smallestCycle.begin(), smallestCycle.end());
- // Print the smallest cycle
- for (int node : smallestCycle) {
- cout << node << " ";
- }
- cout << endl;
- return 0;
- }
- /*5 5
- 1 2 2 4 4 5 5 3 3 2
- 2 3 4 5
- 5 5
- 2 4 2 3 4 3 1 5 5 1
- 1 5*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement