Tango's smart visit

There are cities connected by 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 longg[max];
vector<long longp(max);
vector<long longsize1(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 Along 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 nint mint k,
                     vector<vector<int>> &edges)
{
    for (long long i = 0i < ni++)
    {
        initialize(i);
    }
    for (long long i = 0i < mi++)
    {
        long long a = edges[i][0]b = edges[i][1];

        a--, b--;
        g[a].push_back(b);
        g[b].push_back(a);
        unionFind(ab);
    }
    long long sz[n] = {0};
    long long total = 0;
    for (long long i = 0i < ni++)
    {
        sz[find(i)]++;
    }
    for (long long i = 0i < ni++)
    {
        total += (sz[i] > 0);
    }
    set<long longcomp[n];
    for (long long i = 0i < ni++)
    {
        comp[find(i)].insert(i);
    }
    long long req = totalprev = 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(compcomp + n);
    for (long long i = 0i < ni++)
    {
        for (auto j : comp[i])
        {
            cout << j + 1 << " ";
        }
    }
    cout << "\n";
}
int main()
{
    long long n = 5m = 3k = 2;
    vector<vector<int>> edges = {{12}, {34}, {45}};

    tangoSmartVisit(nmkedges);
    return 0;
}


No comments:

Post a Comment