Cod sursa(job #2450609)

Utilizator r00t_Roman Remus r00t_ Data 23 august 2019 19:13:14
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <queue>

using namespace std;

ifstream fin("darb.in");
ofstream fout("darb.out");

vector<int>vp[100100];
bool viz[100100];
int dst[100100];

void bfs(int x)
{
	int current = x;
	queue<int> q;
	q.push(x);
	viz[x] = 1;
	while (!q.empty())
	{
		current = q.front();
		q.pop();
		for (auto u : vp[current])
		{
			if (viz[u] == 0)
			{
				q.push(u);
				viz[u] = 1;
				dst[u] = dst[current] + 1;
			}
		}
	}
}

int main()
{
	int n;
	fin >> n;
	for (int i = 0; i < n - 1; i++)
	{
		int a, b;
		fin >> a >> b;
		vp[a].push_back(b);
		vp[b].push_back(a);
	}
	int Max = 0, root = 0;
	bfs(1);
	for (int i = 1; i <= n; i++)
	{
		if (Max < dst[i])
		{
			Max = dst[i];
			root = i;
		}
	}

	for (int i = 1; i <= n; i++) viz[i] = 0, dst[i] = 0;

	bfs(root);
	Max = 0;
	for (int i = 1; i <= n; i++)
		Max = max(dst[i], Max);
	fout << Max + 1;

}