Sunday, January 6, 2019

[Spoj]] RTREE - Roger and tree

Author            : Dipu Kumar Mohanto 
                    CSE, Batch - 6
                    BRUR.
Problem Statement : RTREE - Roger and tree
Source            : Spoj
Category          : Graph Theory, Tree
Algorithm         : Tree, DFS
Verdict           : Accepted
#include <bits/stdc++.h>
 
using namespace std;
 
 
static const int maxn = 1e5 + 5;
 
vector <int> tree[maxn];
int firstmax[maxn], secondmax[maxn], pathmax[maxn];
 
void dfs1(int u, int p = -1)
{
      for (int &v : tree[u])
      {
            if (v == p) continue;
            dfs1(v, u);
            if (firstmax[u] < firstmax[v]+1)
            {
                  secondmax[u] = firstmax[u];
                  firstmax[u] = firstmax[v] + 1;
            }
            else if (secondmax[u] < firstmax[v]+1)
            {
                  secondmax[u] = firstmax[v] + 1;
            }
      }
}
 
void dfs2(int u, int p = -1)
{
      for (int &v : tree[u])
      {
            if (v == p) continue;
            dfs2(v, u);
            pathmax[u] = max(pathmax[u], firstmax[u]+secondmax[u]);
            if (pathmax[v] > pathmax[u]) pathmax[u] = pathmax[v]; 
      }
}
 
int main()
{
      int tnode;
      cin >> tnode;
      for (int e = 1; e < tnode; e++)
      {
           int u, v;
           cin >> u >> v; 
           tree[u].push_back(v);
           tree[v].push_back(u);
      }
      int root;
      cin >> root;
      dfs1(root);
      dfs2(root);
      int tquery;
      cin >> tquery;
      while (tquery--)
      {
            int v;
            cin >> v;
            cout << pathmax[v] << endl;
      }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.