﻿ HDU 3045

### HDU 3045

It’s summer vocation now. After tedious milking, cows are tired and wish to take a holiday. So Farmer Carolina considers having a picnic beside the river. But there is a problem, not all the cows consider it’s a good idea! Some cows like to swim in West Lake, some prefer to have a dinner in Shangri-la ,and others want to do something different. But in order to manage expediently, Carolina coerces all cows to have a picnic!
Farmer Carolina takes her N (1<N≤400000) cows to the destination, but she finds every cow’s degree of interest in this activity is so different that they all loss their interests. So she has to group them to different teams to make sure that every cow can go to a satisfied team. Considering about the security, she demands that there must be no less than T(1<T≤N)cows in every team. As every cow has its own interest degree of this picnic, we measure this interest degree’s unit as “Moo~”. Cows in the same team should reduce their Moo~ to the one who has the lowest Moo~ in this team——It’s not a democratical action! So Carolina wishes to minimize the TOTAL reduced Moo~s and groups N cows into several teams.
For example, Carolina has 7 cows to picnic and their Moo~ are ‘8 5 6 2 1 7 6’ and at least 3 cows in every team. So the best solution is that cow No.2,4,5 in a team (reduce (2-1)+(5-1) Moo~)and cow No.1,3,6,7 in a team (reduce ((7-6)+(8-6)) Moo~),the answer is 8.

Input

The input contains multiple cases.
For each test case, the first line has two integer N, T indicates the number of cows and amount of Safe-base line.
Following n numbers, describe the Moo~ of N cows , 1st is cow 1 , 2nd is cow 2, and so on.
Output

One line for each test case, containing one integer means the minimum of the TOTAL reduced Moo~s to group N cows to several teams.

Sample Input

```7 3
8 5 6 2 1 7 6```

Sample Output

`8`

b点优于a点　<=>　g(a,b) ≤ i

b点劣于a点　<=>　g(a,b) > i

AC代码：

```#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=400000+10;

int n,t;
LL Moo[maxn],sum[maxn];
LL dp[maxn];

LL up(int a,int b)
{
return (dp[b]-sum[b]+Moo[b+1]*b)-(dp[a]-sum[a]+Moo[a+1]*a);
}
LL down(int a,int b)
{
return Moo[b+1]-Moo[a+1];
}

int main()
{
while(scanf("%d%d",&n,&t)!=EOF)
{
for(int i=1;i<=n;i++) scanf("%I64d",&Moo[i]);
sort(Moo+1,Moo+n+1);
sum[0]=0;
for(int i=1;i<=n;i++) sum[i]=sum[i-1]+Moo[i];

dp[0]=0;
for(int i=1;i<=min(2*t-1,n);i++) dp[i]=dp[i-1]+Moo[i]-Moo[1];

for(int i=2*t;i<=n;i++)
{
int j=i-t;
{
int a=q[tail-2], b=q[tail-1];
if(up(a,b)*down(b,j)>=up(b,j)*down(a,b)) tail--;
else break;
}
q[tail++]=j;

{
else break;
}