Almost Sorted

View as PDF

Submit solution

Points: 10 (partial)
Time limit: 2.0s
Memory limit: 64M

Problem type

After the lecture on sorting, Diana's CS teacher has given the class a challenge: what's the most efficient way to sort the class list? Students are only allowed to sort by repeatedly swapping two names in the list, and the person who makes the fewest swaps wins.

Diana really wants to win, so she decides to do something sneaky. When showing the teacher her efficient sort, she will omit one of the names in the list, which will let her use fewer swaps. Using her tactical advantage, what is the fewest swaps she has to do?

Input Specifications

The first line of input will contain an integer N (1 \le N \le 1\,000).

The next N lines represent the class list, with one name on each line in capital letters. Names will be unique and only contain uppercase letters.

Output Specifications

For each test case, your program should output the minimum number of swaps Diana needs to sort the list using her trick.

Sample Input 1

3
SAM
DIANA
REBECCA

Sample Output 1

0

Sample Input 2

5
DEREK
MEGAN
BRIAN
BOB
DIANA

Sample Output 2

1

Note: Only 2 cases are shown in this sample.

Explanation

In the first example, removing SAM will leave the list sorted, so no swaps are required.

In the second example, Diana could omit MEGAN and then sort the list by swapping DEREK and BOB.


Note: This is an ECOO (Educational Computing Organization of Ontario) question from 2017, round 1 problem 4.

Comments

There are no comments at the moment.