Cod sursa(job #1728440)

Utilizator theo.stoicanTheodor Stoican theo.stoican Data 12 iulie 2016 21:59:03
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

int n;
vector<vector<int> > graph;
int diameter;
int last; 

void bfs (int x)
{
	vector<bool> visited (n+1, false);
	vector<int> counter (n+1, 0);
	queue<int> q;
	q.push(x);
	visited[x] = true;
	counter[x] = 1;
	while (!q.empty())
	{
		int node = q.front();
		q.pop();
		for (int i = 0; i < graph[node].size(); i++)
		{
			if (!visited[graph[node][i]])
			{
				visited[graph[node][i]] = true;
				counter[graph[node][i]] = counter[node] + 1;
				q.push(graph[node][i]);
				diameter = counter[graph[node][i]];
				last = graph[node][i];
			}
		}
	}
}

int main()
{
	int a,b;
	fin>>n;
	graph.resize(n+1);
	for (int i = 1; i <= n-1; i++)
	{
		fin>>a>>b;
		graph[a].push_back(b);
		graph[b].push_back(a);
	}
	//the first bfs is to find the farthest node from a specific onde
	bfs(1);
	//the second is to find the farthest from the farthest of a specific
	//node
	bfs(last);
	fout<<diameter;
}