Cod sursa(job #2764397)

Utilizator DariusMDarius Feher DariusM Data 20 iulie 2021 19:06:29
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

ifstream f("darb.in");
ofstream g("darb.out");

const int maxVert = 100001;

vector<int> Adj[maxVert];
int dist[maxVert];
int leaf_1;
int n;

void bfs(int source) {
	queue<int> nodes;
	nodes.push(source);
	int front;
	for (int i = 1; i <= n; ++i) {
		dist[i] = -1;
	}
	dist[source] = 0;
	while (!nodes.empty()) {
		front = nodes.front();
		nodes.pop();
		int neighbours = Adj[front].size();
		for (int i = 0; i < neighbours; ++i) {
			if (dist[Adj[front][i]] == -1) {
				dist[Adj[front][i]] = dist[front] + 1;
				nodes.push(Adj[front][i]);
			}
		}
	}
}

int main() {
	int x, y;
	f >> n;
	for (int i = 1; i < n; ++i) {
		f >> x >> y;
		Adj[x].push_back(y);
		Adj[y].push_back(x);
	}
	bfs(1);
	int leaf_1, maxi_dist = 0;
	for (int i = 1; i <= n; ++i) {
		if (dist[i] > maxi_dist) {
			maxi_dist = dist[i];
			leaf_1 = i;
		}
	}
	bfs(leaf_1);
	maxi_dist = 0;
	for (int i = 1; i <= n; ++i) {
		if (dist[i] > maxi_dist) {
			maxi_dist = dist[i];
		}
	}
	g << maxi_dist + 1;
	f.close();
	g.close();
	return 0;
}