longest path in a tree( DFS )
Dec 18, 2018 at 6:47am UTC
Question-
https://www.spoj.com/problems/PT07Z/
Issue-
I am getting time limit exceeded even with dfs. :|
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
#include<iostream>
#include<vector>
using namespace std;
int l=0;
int tree(int start,int prev,int current,int path,vector<int >adj[])
{
if (path>l)
l=path;
for (auto x:adj[current])
{
if (x!=prev)
tree(start,current,x,path+1,adj);
}
return 0;
}
int main()
{
int n;
cin>>n;
vector<int >adj[n+1];
n--;
vector<int >node;
int t1,t2;
for (int i=0;i<n;i++)
{
cin>>t1>>t2;
node.push_back(t1);
if (t1!=t2)
{
node.push_back(t2);
adj[t1].push_back(t2);
adj[t2].push_back(t1);
}
}
for (auto i:node)
{
tree(i,i,i,0,adj);
}
cout<<l;
return 0;
}
Last edited on Dec 18, 2018 at 7:14am UTC
Dec 18, 2018 at 11:42am UTC
1 2
for (auto i:node) //n iterations
tree(i,i,i,0,adj); //O(n)
so you end with O(n^2)
with n=10000 that's too much
hint:
- you may change the root of your tree, but that will not change the distance between nodes v and w
- the node x that's on the largest path will also be the deepest one
Dec 18, 2018 at 3:25pm UTC
@ne555
Omg, thank you that helped so much!!!
I used double dfs, one to find the deepest node, and second for maximum distance.
Topic archived. No new replies allowed.