#C8988. Leaf Nodes Counting and Summing

    ID: 53030 Type: Default 1000ms 256MiB

Leaf Nodes Counting and Summing

Leaf Nodes Counting and Summing

You are given a tree with n nodes labeled from 1 to n and m edges. The tree is undirected and is guaranteed to be connected. Your task is to count the number of leaf nodes and compute the sum of their labels. A node is considered a leaf if its degree is exactly 1, i.e., it is connected to exactly one other node. Note that if the tree consists of a single node, it is not considered a leaf.

The condition for a leaf node is given by the equation:

$$\text{degree}(u) = 1$$

where u is a node in the tree.

inputFormat

The input is read from standard input and has the following format:

n
m
u1 v1
u2 v2
...
num vm

Here:

  • n is the number of nodes.
  • m is the number of edges (note: for a tree, m = n - 1 except when n = 1, in which case m = 0).
  • Each of the next m lines contains two integers ui and vi, indicating an undirected edge between node ui and node vi.

outputFormat

Output to the standard output two integers separated by a space:

leaf_count leaf_sum

where:

  • leaf_count is the number of leaf nodes.
  • leaf_sum is the sum of the labels of all leaf nodes.

For example, if there are 3 leaf nodes whose labels add up to 11, the output should be:

3 11
## sample
5
4
1 2
1 3
3 4
3 5
3 11