#K70617. Tree Validation
Tree Validation
Tree Validation
You are given an undirected graph with n nodes and e edges. The graph is provided as a list of edges, where each edge connects two distinct nodes. Your task is to determine whether the given graph forms a tree.
A graph is a tree if and only if the following conditions hold:
- The graph is connected, i.e. there is a path between any two nodes.
- The graph contains no cycles.
- The number of edges e is exactly n-1.
Input Format: The first line contains two integers n and e, representing the number of nodes and edges, respectively. Each of the next e lines contains two integers u and v, indicating that there is an edge between nodes u and v.
Output Format: Print YES
if the graph is a tree; otherwise, print NO
.
The mathematical condition for a tree can be expressed as follows:
\( e = n - 1 \)
and the graph must be connected (every node is reachable from any other node) with no cycle present.
inputFormat
The input is given via standard input (stdin) and has the following format:
n e u1 v1 u2 v2 ... ue ve
Where:
n
is the number of nodes.e
is the number of edges.- Each of the next
e
lines contains two integersu
andv
representing an undirected edge between nodesu
andv
.
outputFormat
The output should be printed to standard output (stdout) as a single line:
YES
if the graph is a valid tree, or
NO
if it is not.
## sample5 4
1 2
2 3
3 4
4 5
YES