Building Roads

Byteland has cities and  roads between them. The goal is to construct new roads so that there is a route between any two cities.

Your task is to find out the minimum number of roads required, and also determine which roads should be built.

Example:

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

Output:

1 1 3

Approach:

C++

#include <bits/stdc++.h>
using namespace std;
vector<intarr[2000011];
int vis[2000011];
void dfs(int node)
{
    vis[node] = 1;
    for (int child : arr[node])
    {
        if (vis[child] == 0)
            dfs(child);
    }
}
int main()
{
    int n = 4m = 2;
    vector<vector<int>> edges = {{12}, {34}};
    for (int i = 0i < mi++)
    {
        int a = edges[i][0]b = edges[i][1];

        arr[a].push_back(b);
        arr[b].push_back(a);
    }
    int cnt = 0;
    vector<intpath;
    for (int i = 1i <= ni++)
    {
        if (vis[i] == 0)
        {
            path.push_back(i);
            cnt++;
            dfs(i);
        }
    }
    if (cnt == 1)
        cout << 0 << "\n";
    else
    {
        cout << cnt - 1 << "\n";
        for (int i = 0i < path.size() - 1i++)
        {
            cout << path[i] << " " << path[i + 1] << "\n";
        }
    }
}


No comments:

Post a Comment