Tango's smart visit

There are N cities connected by M bidirectional roads. Each of these cities has an Airport which can be used to travel from one to another city regardless of whether these are connected by a road or not.

You’re Charlie, Tango’s best friend.
Tango would be happy if he gets to visit all of these cities using at most K flights.
Provide a sequence that makes him happy. If It's not possible to do so print −1 and if there are multiple sequence output the Lexicographically smallest sequence. 

Note - Tango is okay if he revisits a city but he can't afford more than K flights

Example:

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

Approach

C++

#include <bits/stdc++.h>
using namespace std;
#define max 100005
vector<long long> g[max];
vector<long long> p(max);
vector<long long> size1(max);

void initialize(long long i)
{
    p[i] = i;
    size1[i] = 1;
}

long long find(long long i)
{
    if (p[i] == i)
        return i;
    else
        return p[i] = find(p[i]);
}

void unionFind(long long A, long long B)
{
    long long root_A = find(A);
    long long root_B = find(B);
    if (root_A != root_B)
        if (size1[root_A] < size1[root_B])
        {
            p[root_A] = root_B;
            size1[root_B] += size1[root_A];
        }
        else
        {
            p[root_B] = root_A;
            size1[root_A] += size1[root_B];
        }
}

void tangoSmartVisit(int n, int m, int k,
                     vector<vector<int>> &edges)
{
    for (long long i = 0; i < n; i++)
    {
        initialize(i);
    }
    for (long long i = 0; i < m; i++)
    {
        long long a = edges[i][0], b = edges[i][1];

        a--, b--;
        g[a].push_back(b);
        g[b].push_back(a);
        unionFind(a, b);
    }
    long long sz[n] = {0};
    long long total = 0;
    for (long long i = 0; i < n; i++)
    {
        sz[find(i)]++;
    }
    for (long long i = 0; i < n; i++)
    {
        total += (sz[i] > 0);
    }
    set<long long> comp[n];
    for (long long i = 0; i < n; i++)
    {
        comp[find(i)].insert(i);
    }
    long long req = total, prev = 0;
    if (k < req - 1)
    {
        cout << "-1" << endl;
        return;
    }
    long long p = 0;
    while (p < n && req < k)
    {
        cout << p + 1 << " ";
        comp[find(p)].erase(p);
        if (find(prev) != find(p))
            k--;
        if (comp[find(p)].empty())
            k++;
        prev = p;
        p++;
    }
    sort(comp, comp + n);
    for (long long i = 0; i < n; i++)
    {
        for (auto j : comp[i])
        {
            cout << j + 1 << " ";
        }
    }
    cout << "\n";
}
int main()
{
    long long n = 5, m = 3, k = 2;
    vector<vector<int>> edges = {{1, 2}, {3, 4}, {4, 5}};

    tangoSmartVisit(n, m, k, edges);
    return 0;
}


No comments:

Post a Comment