Planets and Kingdoms

A game has n planets, connected by m teleporters. Two planets a and b belong to the same kingdom exactly when there is a route both from a to and from b to a. Your task is to determine for each planet its kingdom.

Example:

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

Output:

2 1 1 1 2 2

Approach:

C++

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

vector<long longadj1[100005], adj2[100005];
stack<long longst;
long long vis[100005];
void dfs(long long s)
{
    if (vis[s])
        return;
    vis[s] = 1;
    for (auto i : adj1[s])
        dfs(i);
    st.push(s);
}
long long k = 0;
void dfs2(long long s)
{
    if (vis[s])
        return;
    vis[s] = k;
    for (int i : adj2[s])
        dfs2(i);
}
vector<long longplanetsAndKingdom(long long nlong long m,
                                    vector<vector<long long>> &edges)
{

    for (long long i = 0i < mi++)
    {
        long long a = edges[i][0]b = edges[i][1];

        adj1[a].push_back(b);
        adj2[b].push_back(a);
    }
    for (long long i = 1i <= ni++)
    {

        //if not visited call for dfs
        if (!vis[i])
            dfs(i);
    }

    //fill with zeros
    memset(vis0sizeof(vis));

    while (!st.empty())
    {
        long long x = st.top();
        st.pop();
        if (!vis[x])
        {
            k++;
            dfs2(x);
        }
    }

    vector<long longres;
    res.push_back(k);

    for (long long i = 1i <= ni++)
        res.push_back(vis[i]);
    return res;
}
int main()
{
    long long n = 5m = 6;

    vector<vector<long long>> edges = {{12},
                                       {23},
                                       {31},
                                       {34},
                                       {45},
                                       {54}};

    vector<long longres = planetsAndKingdom(nmedges);

    cout << res[0] << "\n";

    for (long long i = 1i < res.size(); i++)
        cout << res[i] << " ";

    return 0;
}


No comments:

Post a Comment