【POJ3709】K-Anonymous Sequence K佚名序列丶 斜率优化DP

题意:n个不降的数,要分成若干连续段,每堆至少m个,每堆里的数都必须一样,不一样可以花费1的费用把某个--,直到同一个段里全一样,求最小花费。

题解:斜率优化DP丶、、、老规矩,动规方程和拆解看代码注释。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 501000
#define inf 0x3f3f3f3f
#define INF 0x3f3f3f3f3f3f3f3fll
/*
	f[i]=f[u]+sum[i]-sum[u]-(i-u)*a[u+1]

	f[u]-sum[u]+u*a[u+1]=i*a[u+1]+f[i]-sum[i]
	y=f[u]-sum[u]+u*a[u+1]
	x=a[u+1]
	k=i
	b=f[i]-sum[i]
*/
using namespace std;
int n,m;
int a[N];
long long sum[N],f[N];
struct Point
{
	long long x,y;
	int id;
	Point(long long _x,long long _y,int _id):x(_x),y(_y),id(_id){}
	Point(){}
}now,q[N];
int l,r;
inline long long xmul(Point i,Point j,Point k){return (j.y-k.y)*(i.x-j.x)-(i.y-j.y)*(j.x-k.x);}
int main()
{
//	freopen("test.in","r",stdin);
//	freopen("my.out","w",stdout);
	int i,g;
	scanf("%d",&g);
	while(g--)
	{
		scanf("%d%d",&n,&m);
		memset(f,0x3f,sizeof(f));
		l=f[0]=0,r=-1;
		for(i=1;i<=n;i++)scanf("%d",&a[i]),sum[i]=sum[i-1]+a[i];
		for(i=m;i<=n;i++)
		{
			if(f[i-m]<INF)
			{
				now=Point(a[i-m+1],f[i-m]-sum[i-m]+(long long)(i-m)*a[i-m+1],i-m);
				while(l<r&&xmul(now,q[r],q[r-1])>=0)r--; // 斜(jk)>=斜(ij) 弹
				q[++r]=now;
			}
			long long K=i;
			while(l<r&&q[l+1].y-q[l].y<=(q[l+1].x-q[l].x)*K)l++; //斜率<=K 跳
			int u=q[l].id;
			f[i]=f[u]+sum[i]-sum[u]-(long long)(i-u)*a[u+1];
		}
		cout<<f[n]<<endl;
	}
	return 0;
}


你可能感兴趣的:(dp,动态规划,sequence,斜率优化,POJ37909,K-Anonymous)