longest path in a tree( DFS )

closed account (1vf9z8AR)
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
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
closed account (1vf9z8AR)
@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.