Friday, August 19, 2022
HomeSoftware DevelopmentMinimal of the Most distances from any node to all different nodes...

Minimal of the Most distances from any node to all different nodes of given Tree

[ad_1]

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

void dfs(vector<int>& d, int node,

         vector<vector<int> >& adj, int dist)

{

    d[node] = dist;

  

    

    for (auto baby : adj[node]) {

        if (dist + 1 < d[child])

            dfs(d, baby, adj, dist + 1);

    }

}

  

int minDist(int N, vector<vector<int> >& edges)

{

    int ans = INT_MAX;

  

    

    vector<vector<int> > adj(N + 1);

    for (auto u : edges) {

        adj[u[0]].push_back(u[1]);

        adj[u[1]].push_back(u[0]);

    }

  

    

    

    for (int i = 1; i <= N; i++) {

  

        

        

        

        vector<int> d(N + 1, INT_MAX);

  

        

        

        dfs(d, i, adj, 0);

  

        int dist = 0;

  

        

        for (int j = 1; j <= N; j++)

            dist = max(dist, d[j]);

  

        

        

        ans = min(ans, dist);

    }

  

    

    return ans;

}

  

int fundamental()

{

    int N = 4;

    vector<vector<int> > edges

        = { { 1, 2 }, { 2, 3 }, { 2, 4 } };

  

    

    cout << minDist(N, edges);

    return 0;

}

[ad_2]

RELATED ARTICLES

Most Popular

Recent Comments