Cod sursa(job #2947802)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 26 noiembrie 2022 18:43:25
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.61 kb
#include <bits/stdc++.h>

using namespace  std;

const int NMAX = 100003;

int n;
int maxDist, farthestNode;

vector<int> g[NMAX];

void dfs(int node, int parent, int dist) {
	if(maxDist < dist) {
		maxDist = dist;
		farthestNode = node;
	}
	for(auto child : g[node])
		if(child != parent)
			dfs(child, node, dist+1);
}

int main() {
	freopen("darb.in", "r", stdin);
	freopen("darb.out", "w", stdout);
	int n;
	scanf("%d", &n);
	for(int i = 1; i < n; i++) {
		int x, y;
		scanf("%d %d", &x, &y);
		g[x].push_back(y);
		g[y].push_back(x);
	}

	dfs(1, -1, 1);
	dfs(farthestNode, -1, 1);

	printf("%d\n", maxDist);
	
	return 0;
}