Round Trip

Byteland has n cities and m roads between them. Your task is to design a round trip that begins in a city, goes through two or more other cities, and finally returns to the starting city. Every intermediate city on the route has to be distinct.

Example:

Input:  n = 5, m = 6, edges = {{1, 3}, {1, 2}, {5, 3}, {1, 5}, {2, 4}, {4, 5}}

Output:

4 1 3 5 1

Approach:

C++

#include <bits/stdc++.h>
using namespace std;
vector<intarr[1000001];
vector<intcolorparent;
int cycle_startcycle_end;
int n;
bool dfs(int nodeint par)
{
    color[node] = 1;
    for (int child : arr[node])
    {
        if (child == par)
            continue;
        if (color[child] == 0)
        {
            parent[child] = node;
            if (dfs(childparent[child]))
                return true;
        }
        else if (color[child] == 1)
        {
            cycle_start = child;
            cycle_end = node;
            return true;
        }
    }
    color[node] = 2;
    return false;
}
void findCycle()
{
    color.assign(n + 10);
    parent.assign(n + 1, -1);
    cycle_start = -1;
    for (int i = 1i <= ni++)
        if (color[i] == 0 && dfs(iparent[i]))
            break;
    if (cycle_start == -1)
        cout << "IMPOSSIBLE\n";
    else
    {
        vector<intcycle;
        cycle.push_back(cycle_start);
        for (int v = cycle_endv != cycle_startv = parent[v])
            cycle.push_back(v);
        cycle.push_back(cycle_start);

        cout << cycle.size() << "\n";
        reverse(cycle.begin(), cycle.end());
        for (int v : cycle)
            cout << v << " ";
        cout << "\n";
    }
}
int main()
{
    int m;
    n = 5m = 6;
    vector<vector<int>> edges = {{13},
                                 {12},
                                 {53},
                                 {15},
                                 {24},
                                 {45}};
    for (int i = 0i < mi++)
    {
        int a = edges[i][0]b = edges[i][1];

        arr[a].push_back(b);
        arr[b].push_back(a);
    }
    findCycle();
    return 0;
}


No comments:

Post a Comment