Pagini recente » Cod sursa (job #2684295) | Cod sursa (job #17919) | Cod sursa (job #2764420) | Cod sursa (job #1033078) | Cod sursa (job #1728440)
#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;
}