Picnic Cows
Time Limit: 8000/4000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
Problem Description
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
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
思路:
题意:
- 有n只奶牛,每只奶牛有有一个满意度
- 要对这n只奶牛进行分组,每组奶牛数量不少于t
- 一旦分组,组内所有奶牛的满意度都会变为最小的满意度
- 求所有组内满意度变化的最小值
抽象:
- 对n个整数分组,每组至少 t 个数字
- 每组的价值为:组内的每个数 - 组内最小的数
- 求所有分组的价值总和的最小值
方法:
- 将所有的整数排序,这样能使得价值最小
- dp[i]表示:前 i 个数的总价值
- sum[i]表示:前 i 个数的和
- a[i]表示:第 i 个数的值
递推公式:
- 每一个数都减去最小的那个数,结果为区间和-最小值 * 区间长度
- dp[i] = dp[j] + sum[i] - sum[j] - a[j + 1] * (i - j),j < i - t + 1
- 化成斜率dp形式
- 分子为:dp[j] - sum[j] + j * a[j + 1] - (dp[k] - sum[k] + k * a[k + 1])
- 分母为:a[j + 1] - a[k + 1]
- 斜率为:i
注意:
- i - t + 1 > t,目的是保证第一组元组至少有 t 个
- 数组用long long
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
#define maxn 400010
long long sum[maxn];//前i个数和
long long dp[maxn];//前i个数总价值
long long a[maxn];//输入的数
long long q[maxn];//队列
long long dt(int i,int j)//递推公式
{
return dp[j]+sum[i]-sum[j]-a[j+1]*(i-j);
}
long long up(int j,int k)//分子
{
return dp[j]-sum[j]+j*a[j+1]-(dp[k]-sum[k]+k*a[k+1]);
}
long long down(int j,int k)//分母
{
return a[j+1]-a[k+1];
}
int main()
{
int head,tail;//队头队尾
int n,t;
while(cin>>n>>t)
{
dp[0]=sum[0]=0;
a[0]=0;
for(int i=1;i<=n;i++)
{
cin>>a[i];//输入数
}
sort(a+1,a+n+1);//排序
for(int i=1;i<=n;i++)
{
sum[i]=sum[i-1]+a[i];//前i项和
}
head=tail=0;
q[tail++]=0;
for(int i=1;i<=n;i++)
{
while(head+1<tail && up(q[head+1],q[head])<=i*down(q[head+1],q[head]))
{
head++;
}
dp[i]=dt(i,q[head]);
int tmp=i-t+1;
if(tmp<t) continue;//保证第一组元组至少有t个
while(head+1<tail && up(tmp,q[tail-1])*down(q[tail-1],q[tail-2])<=up(q[tail-1],q[tail-2])*down(tmp,q[tail-1]))
{
tail--;
}
q[tail++]=tmp;
}
cout<<dp[n]<<endl;
}
return 0;
}