Restaurant
Time limit1sMemory limit128 MB
Split a sequence of N foods into consecutive groups, where a group costs the square of its number of distinct foods, and minimize the total cost.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Divide and conquer, Two pointers, Prefix sum
- Solved
- No attempts yet
Problem
Farmer John's restaurant serves kinds of food to cows.
Each cow has a single favorite food , and Farmer John hands out the food by the following rule:
- The cows entering the restaurant are split into consecutive groups in their arrival order. For example, cuts the line from the very front.
- The cost of serving one group is (the number of distinct favorite foods among the cows in that group). In other words, treating foods as numbers, it is the square of how many distinct numbers appear in the group.
Find the minimum total cost of serving all the cows.
Input
The first line contains two integers and , separated by a space. ()
Each of the next lines contains one favorite food , given in the order the cows arrive. ()
Output
Print, on a single line, the minimum total cost of serving all the cows.
Hint
For example, for the sample input, grouping the cows (in arrival order) as gives a total cost of .