Tidying the Plush Toys
Time limit2sMemory limit512 MB
Given a row of N toys of M types, find the fewest toys to remove so that after reinserting them all toys of each type form one contiguous block.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Bit manipulation, Prefix sum
- Solved
- No attempts yet
Problem
Someone involved with JOI works at a toy store. Today they have to tidy up the plush toy corner of the store.
On the shelf of the plush toy corner, plush toys stand in a row from left to right. Dividers split the shelf into compartments, and each compartment holds one plush toy. The store sells types of plush toys in total, numbered from to . Each of the plush toys on the shelf is one of these types. Every type has at least one plush toy on the shelf.
To make the shelf look better, you want to rearrange the plush toys so that all toys of the same type sit consecutively on the shelf. You rearrange them as follows.
- Choose some of the plush toys and take them off the shelf. The toys that are not taken off stay where they are.
- Put the toys you took off back into the empty compartments of the shelf, in any order you like.
After the rearrangement, all plush toys of the same type must sit consecutively on the shelf. Write a program that finds the minimum number of plush toys you must take off to do this.
Input
The input consists of lines.
The first line contains two integers and (, ) separated by a space: there are plush toys of types.
Each of the next lines contains an integer between and inclusive. The integer on the -th of these lines () is the type of the plush toy in the -th compartment from the left. Every type is guaranteed to have at least one plush toy.
Output
Print, on one line, the minimum number of plush toys you must take off to rearrange the shelf.
Hint
In sample 1, the types of the plush toys are 1, 2, 2, 2, 1, 2, 1 from left to right. To take off as few toys as possible, take off the 1st and 6th toys from the left, then put a type 2 toy in the 1st compartment and a type 1 toy in the 6th compartment. This takes off 2 toys.