Cod sursa(job #1389679)

Utilizator alexb97Alexandru Buhai alexb97 Data 16 martie 2015 15:26:18
Problema Diametrul unui arbore Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#include <cstring>
#define INF 0x3f3f3f3f
using namespace std;

ifstream is("darb.in");
ofstream os("darb.out");

int n;
vector<vector<int> > g;
bitset<100000> sel;
vector<int> d;
int lmax = 0;
int poz;
 
void Bf(int x);
 
int main()
{
	is >> n;
	g = vector<vector<int>>(n+1);
	d = vector<int>(n+1, INF);
	int x, y;
	for(int i = 1; i < n; ++i)
	{
		is >> x >> y;
		g[x].push_back(y);
		g[y].push_back(x); 
	}
	Bf(1);
	for(int j = 1; j <= n; ++j)
	{
		if(d[j] > lmax)
		{	
			lmax = d[j];
			poz = j;
		}
	}
	lmax = 0;
	Bf(poz);
	for(int j = 1; j <= n; ++j)
	{
		lmax = max(lmax, d[j]);
	}
	os << lmax+1;
	is.close();
	os.close();
	return 0;
}

void Bf(int x)
{
	queue<int> Q;
	for(int i = 1; i <= n; ++i)
		d[i] = INF;
	sel.reset();
	sel[x] = 1;
	d[x] = 0;
	Q.push(x);
	while(!Q.empty())
	{
		x = Q.front();
		Q.pop();
		for(const auto & y : g[x])
		{
			if(!sel[y] && d[y] > d[x] + 1)
			{
				sel[y] = 1;
				d[y] = d[x] + 1;
				Q.push(y);
			}
		}
	}
}