Algorithm
problem link- https://www.spoj.com/problems/PT07Z/
PT07Z - Longest path in a tree
You are given an unweighted, undirected tree. Write a program to output the length of the longest path (from one node to another) in that tree. The length of a path in this case is number of edges we traverse from source to destination.
Input
The first line of the input file contains one integer N --- number of nodes in the tree (0 < N <= 10000). Next N-1 lines contain N-1 edges of that tree --- Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u, v <= N).
Output
Print the length of the longest path on one line.
Example
Input: 3 1 2 2 3 Output: 2
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h7gt;
#include <limits.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
#define MOD (ll)1000000007
#define pb push_back
#define EPS 1e-9
#define FOR(i,n) for(int i = 0;i < n; i++)
#define FORE(i,a,b) for(int i = a;i <= b; i++)
#define pi(a) printf("%d\n", a)
#define all(c) c.begin(), c.end()
#define tr(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)
#define gc getchar_unlocked
#define sdi(a, b) si(a);si(b)
#define io ios_base::sync_with_stdio(false);cin.tie(NULL);
#define endl '\n'
#define F first
#define S second
#define FILL(arr, val) memset(arr, val, sizeof(arr))
#define read(arr, n) for(int i = 0;i < n; i++)cin>>arr[i];
#define sp ' '
template <typename T> T gcd(T a, T b){return (b==0)?a:gcd(b,a%b);}
template <typename T> T lcm(T a, T b){return a*(b/gcd(a,b));}
template <typename T> T mod_exp(T b, T p, T m){T x = 1;while(p){if(p&1)x=(x*b)%m;b=(b*b)%m;p=p>>1;}return x;}
template <typename T> T invFermat(T a, T p){return mod_exp(a, p-2, p);}
template <typename T> T exp(T b, T p){T x = 1;while(p){if(p&1)x=(x*b);b=(b*b);p=p>>1;}return x;}
void si(int &x){
register int c = gc();
x = 0;
int neg = 0;
for(;((c<48 || c>57) && c != '-');c = gc());
if(c=='-') {neg=1;c=gc();}
for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
if(neg) x=-x;
}
const int MAXN = 10005;
vector<int> adj[MAXN];
bool vis[MAXN];
int currentMax;
int vertofound;
void dfs(int source, int maxlen){
vis[source] = 1;
if(maxlen > currentMax){
currentMax = maxlen;
vertofound = source;
}
for(int i = 0;i < adj[source].size(); i++){
if(!vis[adj[source][i]])
dfs(adj[source][i], maxlen+1);
}
}
int main(){
io;
currentMax = INT_MIN;
int nodes;
cin >> nodes;
for(int i = 1;i <= nodes-1; i++){
int a, b;
cin >> a >> b;
adj[a].pb(b);
adj[b].pb(a);
}
dfs(1, 0);
for(int i = 0;i <= nodes; i++)
vis[i] = 0;
dfs(vertofound, 0);
cout << currentMax << endl;
return 0;
}
Copy The Code &
Try With Live Editor
Input
1 2
2 3
Output
Demonstration
SPOJ Solution-Longest path in a tree-Solution in C, C++, Java, Python