-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHackerrank_interestingtree.cpp
More file actions
99 lines (97 loc) · 1.95 KB
/
Copy pathHackerrank_interestingtree.cpp
File metadata and controls
99 lines (97 loc) · 1.95 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<bits/stdc++.h>
using namespace std;
vector<int>arr[100000];
int visited[100000];
int depth[100000];
int H[100000];
int maxi(int a,int b)
{
if(a>b)
return a;
else return b;
}
int precompute(int i)
{
//cout<<endl<<"Hello->>"<<i;
int links = arr[i].size();
vector<int>tempArr;
vector<int>height;
//memset(tempArr,0,sizeof(tempArr));
int pp = 0;
for(int j=0;j<arr[i].size();j++)
{
if(!visited[arr[i][j]])
{
visited[arr[i][j]]=1;
int q = precompute(arr[i][j]);
tempArr.push_back(q);
height.push_back(H[arr[i][j]]);
pp = j;
//cout<<i<<"piushd"<<H[arr[i][j]]<<" "<<(arr[i][j])<<endl;
}
}
sort(tempArr.begin(),tempArr.end());
sort(height.begin(),height.end());
/*for(int j=0;j<height.size();j++)
{
cout<<"node"<<i<<height[j]<<" "<<tempArr[j]<<endl;
}*/
if(tempArr.size()==0)
{depth[i]= 0;
H[i]=0;
return 0;
}
int max1 = 0;
int max2 =0;
if(tempArr.size()==1)
{
max1 = tempArr[0];
//depth[i]=tempArr[0];
max2=height[0]+1;
//depth[i]=maxi(max2,max1);
}
if(tempArr.size()>=2)
{
max2=height[height.size()-1]+height[height.size()-2]+2;
max1 = tempArr[tempArr.size()-1];
}
//cout<<"returnde"<<depth[i];
depth[i]=maxi(max2,max1);
H[i]=height[height.size()-1]+1;
return depth[i];
//cout<<"Hello";
}
int main()
{
int N;
cin>>N;
int i = 0;
//vector<int>arr[N];
for(i=0;i<N-1;i++)
{
int p,q;
cin>>p>>q;
arr[p-1].push_back(q-1);
arr[q-1].push_back(p-1);
//cout<<"Success";
}
memset(visited,0,sizeof(visited));
memset(H,0,sizeof(H));
int root;
cin>>root;
visited[root-1]=1;
precompute(root-1);
int q;
cin>>q;
/*for(int i=0;i<N;i++)
{
cout<<endl<<i<<"depth"<<depth[i]<<"Height"<<H[i];
}*/
while(q--)
{
int r;
cin>>r;
cout<<depth[r-1]<<endl;
}
return 0;
}