标签:
Description
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko‘s Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.
Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.
Ryouko‘s notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from pagex to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is .
Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≤ x, y ≤ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place.
Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.
Input
The first line of input contains two integers n and m (1 ≤ n, m ≤ 105).
The next line contains m integers separated by spaces: a1, a2, ..., am(1 ≤ ai ≤ n).
Output
Print a single integer — the minimum number of pages Ryouko needs to turn.
Sample Input
4 6
1 2 3 4 3 2
3
10 5
9 4 3 8 8
6
这道题求最小的相邻差值和的最小值。用暴力可以解决。但是数据量是1e5,所以不能简单的暴力。要用一点优化。
首先把没有经过合并的所有的翻页的数计算出来,保存在sum中。然后将某个页码的前缀和后缀分别统计。对每一个页码的关联页码排序,将该页码换成关联页码的
中间大小的页码,重新计算翻页的次数。对所有的页码计算一次之后,取它们当中最小的那个。
这里分析一下,为什么取关联页码的中间大的那个页码可以得到局部最小。如果每个页码都能取到局部最小的值,那么对所有的局部最小值取局部最小的值,得到的就是最小
的值。 所以要分析为什么可以取中间的值来得到局部最小的值。
我们举一个例子: 对于页码1,它的关联页码是:2 5 6 8 10;那么由页码1贡献的翻页次数就是:2-1 + 5-1 + 6-1 + 8-1 + 10-1;
取中间的值重新计算新的贡献的翻页的次数: 6-2 + 6-5 +6-6 + 8-6 + 10-6 。
CodeForces 433C Ryouko's Memory Note-暴力
标签:
原文地址:http://www.cnblogs.com/superxuezhazha/p/5375208.html