#K84527. Tree Diameter Operation Count
Tree Diameter Operation Count
Tree Diameter Operation Count
Given an undirected tree (a connected acyclic graph) with \(N\) nodes and exactly \(N-1\) edges, your task is to determine the minimum number of operations required to find the tree's diameter. The diameter of a tree is defined as the longest path between any two nodes. Using the formula below, the diameter \(D\) of a tree is given by:
[ D = \max { \text{dist}(u, v) : u,v \in T } ]
It can be proven that for any tree with at least two nodes, at most one operation is required to determine the diameter. Therefore, if the tree has at least one edge, the answer is always 1. Write a program that, given the tree structure, prints the required number of operations for each test case.
inputFormat
The first line contains an integer \(T\) (the number of test cases). Each test case is described as follows:
- The first line contains an integer \(N\) (the number of nodes in the tree).
- The following \(N-1\) lines each contain two space-separated integers \(u\) and \(v\), representing an edge between nodes \(u\) and \(v\).
Note: It is guaranteed that the input describes a valid tree.
outputFormat
For each test case, output a single integer on a separate line: the minimum number of operations required to determine the tree's diameter.
If the tree has less than two nodes (i.e. no edges), output -1.
## sample2
4
1 2
2 3
2 4
5
1 2
1 3
3 4
3 5
1
1
</p>