Mail Delivery

Your task is to deliver mail to the inhabitants of a city. For this reason, you want to find a route whose starting and ending point are the post office, and that goes through every street exactly once.

Example:

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

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<pair<intint>> adj[100005];
int vis[200005];

void mailDelivery(int nint m,
                  vector<vector<int>> &edges)
{

    for (int i = 0i < mi++)
    {
        int u = edges[i][0];
        int v = edges[i][1];

        adj[u].push_back({vi});
        adj[v].push_back({ui});
    }
    for (int i = 1i <= ni++)
    {
        if (adj[i].size() & 1)
        {
            cout << "IMPOSSIBLE";
            return;
        }
    }
    stack<intst;
    st.push(1);
    vector<intpath;
    while (!st.empty())
    {
        int v = st.top();
        int f = 0;
        while (!adj[v].empty())
        {
            pair<intintp = adj[v].back();
            adj[v].pop_back();
            if (!vis[p.second])
            {
                st.push(p.first);
                vis[p.second] = 1;
                f = 1;
                break;
            }
        }
        if (!f)
        {
            path.push_back(v);
            st.pop();
        }
    }
    if (path.size() != m + 1)
    {
        cout << "IMPOSSIBLE";
        return;
    }
    for (int i : path)
        cout << i << " ";
}
int main()
{
    int n = 6m = 8;

    vector<vector<int>> edges = {{12},
                                 {13},
                                 {23},
                                 {24},
                                 {26},
                                 {35},
                                 {36},
                                 {45}};

    mailDelivery(nmedges);

    return 0;
}


No comments:

Post a Comment