## CCO '21 P5 - Bread First Search

View as PDF

Points: 20 (partial)
Time limit: 1.0s
Memory limit: 1G

Author:
Problem type

There are towns in a network of undirected roads. Each road connects one pair of towns. The government has decided to conduct a breadth first search, which means finding an ordering of the towns such that if the ordering begins with :

• Each town except for is adjacent to another town given earlier in the order.
• The towns are given in non-decreasing order of distance to . Here, distance means the minimum number of roads that need to be traversed to reach a town.

However, someone mistakenly did a bread first search. They found the ordering (this was obtained by sorting the towns in increasing order of bread production).

To cover up this embarrassment, the government would like to build new roads such that is also a possible breadth first search ordering. The new roads can be built between any two towns. What is the minimum possible number of roads that need to be built?

#### Input Specification

The first line contains the two integers and .

The -th of the next lines contains the two integers and , representing the two endpoints of the -th road. It is guaranteed that and there is at most one road between any two towns.

For 5 of the 25 available marks, .

For an additional 6 of the 25 marks available, .

#### Output Specification

On a single line, output the minimum number of roads that must be constructed.

#### Sample Input 1

2 0

#### Sample Output 1

1

#### Explanation for Sample Output 1

For 1, 2 to be a breadth first search ordering, a road between towns 1 and 2 must be built.

#### Sample Input 2

6 3
1 3
2 6
4 5

#### Sample Output 2

2

#### Explanation for Sample Output 2

By building a road between 1 and 2 and a road between 1 and 4, the sequence of distances becomes which is in non-decreasing order.