Largest cycle in a tree

You are given a tree of N nodes and N1 edges. Now you need to select two nodes a and b in the tree such that the cycle that will be formed after adding an edge between the two nodes a and b, its length should be maximum. If there is more than one possible answer, you can output any of them.

Example:

Input:  N = 7, edges = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}, {3, 7}}
Output: 4 6

Approach

C++

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

vector<intadj[100001];

int N;
pair<intintbfs(int u)
{
    queue<intq;
    int dist[N + 1];
    memset(dist, -1sizeof(dist));

    q.push(u);

    while (!q.empty())
    {
        u = q.front();
        q.pop();

        for (auto i : adj[u])
        {
            if (dist[i] == -1)
            {
                dist[i] = dist[u] + 1;
                q.push(i);
            }
        }
    }

    int maxDist = 0node;

    for (int i = 1i <= Ni++)
    {
        if (dist[i] > maxDist)
        {
            maxDist = dist[i];
            node = i;
        }
    }
    return make_pair(nodemaxDist);
}

pair<intintlargestCycle(vector<vector<int>> edges)
{
    //create the graph
    for (int i = 0i < edges.size(); i++)
    {
        int u = edges[i][0];
        int v = edges[i][1];

        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    pair<intintnode1node2;
    node1 = bfs(1);

    node2 = bfs(node1.first);

    return make_pair(node1.firstnode2.first);
}
int main()

{

    N = 7;

    vector<vector<int>> edges = {{12},
                                 {13},
                                 {24},
                                 {25},
                                 {36},
                                 {37}};

    pair<intintres = largestCycle(edges);

    cout << res.first << " " << res.second << "\n";

    return 0;
}


No comments:

Post a Comment