这题是三分查找模板题,虽然还没弄明白三分查找的原理,还是先放在这里吧。。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include<algorithm>
using namespace std;
__int64 a[2000000];
__int64 Abs(__int64 x)
{
return x>0?x:-x;
}
__int64 Cal(int x,int c,int n)
{
__int64 ans = 0;
int i;
for(i = 1; i < x; i += c)
{
ans += Abs(a[i]-a[x]);
}
for(i = n; i > x; i -= c)
{
ans += Abs(a[i]-a[x]);
}
return ans*2;
}
__int64 find_min_num(__int64 *arr, int begin, int end,int c,int n)
{
if(begin == end)
return 0;
int mid, midmid;
__int64 max;
__int64 t1,t2;
while (begin < end)
{
if (begin + 1 == end)
{
t1 = Cal(begin,c,n);
t2 = Cal(end,c,n);
max = t1 < t2 ? t1 : t2;
return max;
}
mid = (begin + end) / 2;
if (mid + 1 == end)
{
midmid = (mid + end) / 2 + 1;
}
else
{
midmid = (mid + end) / 2;
}
if (midmid == end)
{
t1 = Cal(begin,c,n);
t2 = Cal(mid,c,n);
max = t1 < t2 ? t1 : t2;
t1 = Cal(end,c,n);
max = max < t1 ? max : t1;
return max;
}
t1 = Cal(mid,c,n);
t2 = Cal(midmid,c,n);
if (t1 <= t2)
end = midmid;
else
begin = mid;
}
return Cal(mid,c,n);
}
int main()
{
int n, m, i;
scanf("%d%d",&n,&m);
for(i=1; i<=n; i++)
scanf("%I64d",&a[i]);
printf("%I64d\n",find_min_num(a,1,n,m,n));
return 0;
}