HTML & JS
#include<bits/stdc++.h>
using namespace std;
class Tree{
    int N;
    list<int> *adj;
    int *dist;
    int prevdis;
public:

    Tree(int n){
        this->N = n;
        adj = new list<int>[N+1];
        dist = new int[N+1];
        memset(dist,-1,sizeof(int) * (N + 1));
        prevdis = 0;
    }

    void AddEdge(int u,int v){
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    pair<int,int> DFS(int* dist,int u){
        dist[u]=prevdis;
        for(auto it=adj[u].begin();it!=adj[u].end();it++){

            int t = *it;


            if(dist[t]==-1){
                dist[t] = dist[u]+1;
                prevdis = dist[t];
                DFS(dist,t);
            }
        }

        int max_IND = 0, max_dist = 0;
        for(int i=1;i<=N;i++){
            if(dist[i]>max_dist){
                max_dist = dist[i];
                max_IND = i;
            }
        }

        return make_pair(max_IND,max_dist);
    }


    void path(){

        pair<int,int>t1,t2;
        memset(dist,-1,sizeof(int) * (N + 1));
        t1 = DFS(dist,1);

        memset(dist,-1,sizeof(int) * (N + 1));
        prevdis = 0;
        t2 = DFS(dist,t1.first);
        cout<<t2.second<<"\n";
    }
};


int main(){
    int t;
    cin>>t;
    Tree T(t);
    int u,v;
    for(int i=1;i<t;i++){
        cin>>u>>v;
        T.AddEdge(u,v);
    }
    T.path();
    return 0;
}



Generated URL:

Output:

3
Report Bug