Advertisement
ryuk2603

Spoj_LongestPathInATree

Nov 20th, 2019
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. // Spoj: PT07Z - Longest path in a tree
  2. // https://www.spoj.com/problems/PT07Z/
  3.  
  4. #include<bits/stdc++.h>
  5. #define MAX 10001
  6. #define INF INT_MAX
  7. using namespace std;
  8.  
  9. void bfs(int source, vector<int> graph[], int dist[], int N){
  10.     for(int i=0; i<=N; i++) dist[i] = -1;
  11.     dist[source] = 0;
  12.     queue<int> q;
  13.     q.push(source);
  14.     while ( !q.empty() ){
  15.         int cur = q.front();
  16.         q.pop();
  17.         for(int i=0; i<graph[cur].size(); i++){
  18.             int next = graph[cur][i];
  19.             if( dist[next] == -1 ){
  20.                 q.push(next);
  21.                 dist[next] = dist[cur] + 1;
  22.             }
  23.         }
  24.     }
  25. }
  26.  
  27. int main()
  28. {  
  29.     vector<int> graph[MAX];
  30.     int N, u, v;
  31.     int dist[MAX];
  32.     scanf("%d", &N);
  33.     for(int i=0; i<N-1; i++){
  34.         scanf("%d %d", &u, &v);
  35.         graph[u].push_back(v);
  36.         graph[v].push_back(u);
  37.     }
  38.     bfs(1, graph, dist, N);
  39.     int maxDist = -1;
  40.     int indx;
  41.     for(int i=1; i<=N; i++){
  42.         if(dist[i] > maxDist){
  43.             maxDist = dist[i];
  44.             indx = i;
  45.         }
  46.     }
  47.     bfs(indx, graph, dist, N);
  48.     maxDist = -1;
  49.     for(int i=1; i<=N; i++){
  50.         if(dist[i] > maxDist)
  51.             maxDist = dist[i];
  52.     }
  53.     printf("%d\n", maxDist);
  54.  
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement