BZOJ 1911 APIO 2010 特别行动队 斜率优化DP

题目大意:有一些排列好的士兵,现在要把他们组成一些队伍,每个队伍的战斗力为ax^2 + bx + c,其中x是队伍的权值和。


思路:我还能不能和斜率优化DP好好的玩耍了。。这公式推了三次才推对。。

裸DP方程:f[i] = f[j] + (sum[i] - sum[j]) ^ 2 * a + (sum[i] - sum[j]) * b + c

然后展开。

f[i] = f[j] + a * sum[i] ^ 2 - 2 * a * sum[i] * sum[j] + a * sum[j] ^ 2 + b * sum[i] - b * sum[j] + c

然后整理,准备斜率优化,最后得到

f[j] + a * sum[j] ^ 2 - b * sum[j] = 2 * a * sum[i] * sum[j] + f[i] - a * sum[i] ^ 2 - b * sum[i] - c

y = f[j] + a * sum[j] ^ 2 - b * sum[j]

k = 2 * a * sum[i]

x = sum[j]

剩下的就简单了。


CODE:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 1000010
using namespace std;

struct Point{
	long long x,y;
	
	Point(long long _ = 0,long long __ = 0):x(_),y(__) {}
}q[MAX];

int cnt,a,b,c;
long long src[MAX],sum[MAX],f[MAX];
int front,tail;

inline double GetSlope(const Point &p1,const Point &p2)
{
	return (double)(p2.y - p1.y) / (p2.x - p1.x);
}

inline void Insert(long long x,long long y)
{
	Point temp(x,y);
	while(tail - front >= 2)
		if(GetSlope(q[tail],temp) > GetSlope(q[tail - 1],q[tail]))
			--tail;
		else	break;
	q[++tail] = temp;
}

inline Point GetAns(double slope)
{
	while(tail - front >= 2)
		if(GetSlope(q[front + 1],q[front + 2]) > slope)
			++front;
		else	break;
	return q[front + 1];
}

int main()
{
	cin >> cnt >> a >> b >> c;
	for(int i = 1; i <= cnt; ++i) {
		scanf("%lld",&src[i]);
		sum[i] = sum[i - 1] + src[i];
	}
	front = tail = 0;
	for(int i = 1; i <= cnt; ++i) {
		Insert(sum[i - 1],f[i - 1] + a * sum[i - 1] * sum[i - 1] - b * sum[i - 1]);
		Point p = GetAns(2 * a * sum[i]);
		f[i] = p.y + a * sum[i] * sum[i] - 2 * a * sum[i] * p.x + b * sum[i] + c;
	}
	cout << f[cnt] << endl;
	return 0;
}


你可能感兴趣的:(dp,斜率优化,bzoj,Apio2010,斜率优化DP)