Cod sursa(job #2195828)

Utilizator WebDesignbyTMGhiorghiu Ioan-Viorel WebDesignbyTM Data 17 aprilie 2018 13:59:17
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.67 kb
#define DM 100001
#define inf 0x3f3f3f3f
#include <cstring>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

ifstream fi ("darb.in");
ofstream fo ("darb.out");
int n, a, b, mx, dst[DM];
queue <int> q;
vector <int> v[DM];

void bfs(int x)
{
	memset(dst, inf, sizeof(dst));
	dst[x] = 0;
	mx = x;
	q.push(x);
	while (!q.empty())
	{
		a = q.front();
		b = dst[a];
		q.pop();
		if (b > dst[mx])
			mx = a;
		for (auto i:v[a])
			if (dst[i] > b + 1)
			{
				dst[i] = b + 1;
				q.push(i);
			}
	}
}

int main()
{
	fi >> n;
	for (int i = 1; i < n; ++i)
	{
		fi >> a >> b;
		v[a].push_back(b);
		v[b].push_back(a);
	}
	bfs(1);
	bfs(mx);
	fo << dst[mx] + 1;
	return 0;
}