-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDiameter_of_Tree.cpp
53 lines (43 loc) · 956 Bytes
/
Diameter_of_Tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Vivek Rai
// Blazer_007
// https://www.spoj.com/problems/PT07Z/
#include<bits/stdc++.h>
#define ll long long int
#define pb push_back
const int N = 1e5+5;
using namespace std;
ll n;
std::vector<vector<ll> > adjList(N);
ll max_depth[N];
ll ans = 0 ;
void dfs(ll i,ll par){
priority_queue <ll> pq;
ll mx = 0;
for(auto it: adjList[i]){
if(it != par){
dfs(it,i);
pq.push(max_depth[it]+1);
mx = max(mx,max_depth[it]+1);
}
}
max_depth[i] = mx;
ll dia = 0;
if(pq.size())
dia += pq.top(),pq.pop();
if(pq.size())
dia += pq.top(),pq.pop();
ans = max(ans,dia);
}
signed main()
{
cin>>n;
for(ll i=1;i<=n-1;i++){
ll a,b;
cin>>a>>b;
adjList[a].pb(b);
adjList[b].pb(a);
}
dfs(1,0);
cout<<ans<<endl;
return 0;
}