Problem Link
#include<iostream>
#include <vector>
#include <cmath>
using namespace std;
bool visited[1000001];
int maxDistance;
int maxDistantVertex;
int dfs(int s, vector<int> graph[], int distance)
{
visited[s] = true;
if(distance > maxDistance)
{
maxDistance = distance;
maxDistantVertex = s;
}
for(int v = 0; v < graph[s].size(); v++)
{
if(!visited[graph[s][v]])
{
dfs(graph[s][v], graph, distance + 1);
}
}
return maxDistantVertex;
}
int main()
{
int t, n, a, b;
cin >> t;
while(t--)
{
cin >> n;
vector<int> graph[n];
for(int i = 0; i < n - 1; i++)
{
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for(int i = 0; i < n; i++)
{
visited[i] = false;
}
maxDistance = 0;
int vertex = dfs(0, graph, 0);
for(int i = 0; i < n; i++)
{
visited[i] = false;
}
maxDistance = 0;
dfs(vertex, graph, 0);
if(maxDistance % 2 == 0)
{
cout << maxDistance / 2 << endl;
}
else
{
cout << (maxDistance + 1) / 2 << endl;
}
}
}
Comments
Post a Comment