c++ - Finding longest path in an undirected tree -


i trying find longest path in undirected tree (http://www.spoj.com/problems/pt07z/) , made following code.

#include <iostream> #include <vector>  using namespace std;  vector< vector<int> > graph; int q=0, m = -1;                                // m largest path , q 1 of end vertex of path  void dfs(int i, int count, vector<bool>& v) {     v[i] = true;     for(int j=0;j<graph[i].size();j++)     {         if(!v[graph[i][j]])         {             count++;                            // count length of path starting vertex current vertex             dfs(graph[i][j], count, v);         }     }     if(count>m)     {         m= count;         q=i;     }     count--;                                    // decreasing count since method return calling function }   int main() {     int n, x, i, y;     cin>>n;     graph = vector< vector<int> >(n);     vector<bool> visited(n);     vector<bool> v(n);     for(i=0;i<n-1;i++)     {         cin>>x>>y;         x--, y--;         graph[x].push_back(y);         graph[y].push_back(x);     }     dfs(0, 0, visited);     m=-1;     cout<<q<<endl;     dfs(q, 0, v);     cout<<q<<endl;     cout<<m<<endl; } 

can tell me wrong here because getting wrong value of maximum length of path (m) though end vertices of longest path correct (atleast on test cases have tried). have tried implement following algorithm here:

algorithm:

  1. run dfs node find farthest leaf node. label node t.
  2. run dfs find farthest node t.
  3. the path found in step 2 longest path in tree.

some test cases: first:

17 1 2 1 3 2 4 2 5 3 6 3 7 6 8 6 9 8 10 9 11 7 12 7 13 13 14 13 15 15 16 15 17 

correct answer test case 7.

second:

7 1 2 1 3 2 4 2 5 3 6 3 7 

correct answer test case 4.

just remove count++ 'for' loop , remove count--;

and keep 'count++' @ start of fucntion.

void dfs(int i, int count, vector<bool>& v) {     count++;     v[i] = true;     for(int j=0;j<graph[i].size();j++)     {        if(!v[graph[i][j]])         {             dfs(graph[i][j], count, v);         }     }     if(count>m)     {         m= count;         q=i;     }  } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -