-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest_Path_In_A_Tree.cpp
89 lines (63 loc) · 1.21 KB
/
Longest_Path_In_A_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
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
// by jvpcms
/* The problem consists of receiving a data set
that describes a tree graph and identifying
the length of the longest possible path.
Keywords: Graph Theory, BFS. */
#include<bits/stdc++.h>
using namespace std;
const int N = 1e4 + 5;
bool vis[N];
int layer[N];
vector<int> adj [N];
int bfs(int o)
{
memset(vis, 0, N);
queue<int> q;
q.emplace(o);
int edge = o;
while (!q.empty())
{
int u = q.front();
q.pop();
if (!vis[u])
{
vis[u] = 1;
for (auto i : adj[u]) if (!vis[i])
{
q.emplace(i);
edge = i;
}
}
}
return edge;
}
void dfs(int o)
{
vis[o] = 1;
for (auto i : adj[o]) if (!vis[i])
{
layer[i] = layer[o] + 1;
dfs(i);
}
return;
}
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n - 1; i++)
{
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
int e1 = bfs(1);
int e2 = bfs(e1);
memset(vis, 0, N);
memset(layer, 0, N);
dfs(e1);
cout << layer[e2];
return 0;
}