http://codeforces.com/problemset/problem/427/E

Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.

As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station.

The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.

Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.

Input

The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain nintegers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.

The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane.

Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.

Output

Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.

 

题意:n个罪犯在x轴上,你要选择一点建立监狱,把罪犯都抓回来,一次最多抓m人回来,问最小的总路程。

思路:找n个位置的中位数作为监狱地点,先搞好一边,再搞另一边。搞每一边时,优先拉回来最远的,再拉近的。

画个图,<1>应该最优点是中位数位置作为监狱。

<2>对于确定的监狱位置,怎么拉罪犯最优?首先,应该先一边,再另一边,因为每次取m个取决于最远的罪犯。然后,先一边要优先拉远的还是近的?远的。如最后一个样例,比如123456789,10,11,中位数6,m=2,先拉45,再拉23,最后拉1,这样很不优,应该先45,再23,最后1。

至于写法,可以模拟如上所述,也可以维护当前需要处理的区间,逐渐缩区间。

#include<bits/stdc++.h>
using namespace std;
#define maxn 1000000+1000

long long n,m,a[maxn];
long long ans;

int main()
{
	//freopen("input.in","r",stdin);
	cin>>n>>m;
	for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
	int l=1,r=n;
	while(l<r)
	{
		ans+=(a[r]-a[l])*2;
		l+=m;
		r-=m;
	}
	cout<<ans<<endl;
	return 0;	
}