Cod sursa(job #1259558)

Utilizator sunt_emoSunt emo sunt_emo Data 10 noiembrie 2014 10:37:05
Problema Diametrul unui arbore Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <fstream>
#include <vector>

struct Arb
{
  int id;
  std::vector<Arb *> children;
  Arb(int id): id(id) {}
};

int parcurg(const Arb *root, int depth, std::vector<int> &maxs)
{
  if (root->children.empty())
  {
	if (depth > maxs[0])
	  maxs[1] = maxs[0], maxs[0] = depth;
	if (depth > maxs[1])
	  maxs[1] = depth;
	return maxs[0] + maxs[1];
  }
  for (int i = 0; i < (int) root->children.size(); i++)
    parcurg(root->children[i], depth + 1, maxs);
  
  return maxs[0] + maxs[1];
}

int main()
{
  std::ifstream in("darb.in");
  std::ofstream out("darb.out");
  
  int n;
  
  in >> n;
  
  std::vector<Arb *> data(n + 1, (Arb *) 0);
  for (int i = 0; i < n; i++)
  {
    int x, y;
	in >> x >> y;
	if (data[x] == 0)
	  data[x] = new Arb(x);
	if (data[y] == 0)
	  data[y] = new Arb(y);
	data[x]->children.push_back(data[y]);
  }
  
  std::vector<int> t(2, -1);
  out << parcurg(data[1], 0, t) << '\n';
  
  in.close(), out.close();
}