-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathN-aryTree DP.cpp
60 lines (53 loc) · 1.23 KB
/
N-aryTree DP.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
54
55
56
57
58
59
60
#include<bits/stdc++.h>
using namespace std;
class NaryTree{
private:
int n;
vector<int> *arr;
public:
NaryTree(int n){
this->n = n;
arr = new vector<int>[n];
}
void addEdge(int u, int v){
arr[u].push_back(v);
}
int diameter(int u, int &res){
if(arr[u].size() == 0)
return 1;
else{
int max1 = 0, max2 = 0;
for(int i = 0; i < arr[u].size(); i++){
int temp = diameter(arr[u][i], res);
if(temp > max1){
max2 = max1;
max1 = temp;
}
else if(temp > max2)
max2 = temp;
}
if(res < max1 + max2 + 1)
res = max1 + max2 + 1;
return max(max1, max2) + 1;
}
}
};
int main(){
NaryTree root(13);
int res = 0;
root.addEdge(0, 1);
root.addEdge(0, 2);
root.addEdge(0, 3);
root.addEdge(1, 4);
root.addEdge(1, 5);
root.addEdge(1, 6);
root.addEdge(6, 7);
root.addEdge(6, 9);
root.addEdge(7, 8);
root.addEdge(3, 10);
root.addEdge(3, 11);
root.addEdge(10, 12);
root.diameter(0, res);
cout << res << endl;
return 0;
}