Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Spoj: PT07Z - Longest path in a tree
- // https://www.spoj.com/problems/PT07Z/
- #include<bits/stdc++.h>
- #define MAX 10001
- #define INF INT_MAX
- using namespace std;
- void bfs(int source, vector<int> graph[], int dist[], int N){
- for(int i=0; i<=N; i++) dist[i] = -1;
- dist[source] = 0;
- queue<int> q;
- q.push(source);
- while ( !q.empty() ){
- int cur = q.front();
- q.pop();
- for(int i=0; i<graph[cur].size(); i++){
- int next = graph[cur][i];
- if( dist[next] == -1 ){
- q.push(next);
- dist[next] = dist[cur] + 1;
- }
- }
- }
- }
- int main()
- {
- vector<int> graph[MAX];
- int N, u, v;
- int dist[MAX];
- scanf("%d", &N);
- for(int i=0; i<N-1; i++){
- scanf("%d %d", &u, &v);
- graph[u].push_back(v);
- graph[v].push_back(u);
- }
- bfs(1, graph, dist, N);
- int maxDist = -1;
- int indx;
- for(int i=1; i<=N; i++){
- if(dist[i] > maxDist){
- maxDist = dist[i];
- indx = i;
- }
- }
- bfs(indx, graph, dist, N);
- maxDist = -1;
- for(int i=1; i<=N; i++){
- if(dist[i] > maxDist)
- maxDist = dist[i];
- }
- printf("%d\n", maxDist);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement