HDU 3045 MAX Average Problem

斜率优化DP

dp[i] =max(dp[i],dp[j]+sum[i]-sum[j]-(i-j)*a[j+i]);


#include <cstdio>
#include <iostream>
#include <string.h>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
#define ll long long
const int N = 500005;
ll dp[N], sum[N], a[N];
int q[N];
int n, m, head ,tail;
ll getdp(int i, int j){
	return dp[j] + sum[i] - sum[j] - (i-j)*a[j+1];
}
ll getup(int j, int k){
	return dp[j] - sum[j] + j * a[j+1] - (dp[k] - sum[k] + k * a[k+1]);
}
ll getdown(int j, int k){
	return a[j+1] - a[k+1];
}
int main(){
	int t;
	while(~scanf("%d%d",&n,&t)){
		dp[0] = sum[0] = 0;
		for(int i = 1; i <= n; i++){
			scanf("%I64d",a+i);
		}
		sort(a+1,a+1+n);
		for(int i = 1; i <= n; i++)sum[i] = sum[i-1] + a[i];
		head = tail = 0;
		q[tail++] = 0;
		for(int i = 1; i <= n; i++){
			while(head+1 < tail && getup(q[head+1],q[head]) <= i * getdown(q[head+1],q[head]))
				head++;
			dp[i] = getdp(i,q[head]);
			int j = i - t +1;
			if(j < t)continue;
			while(head+1 < tail && getup(j,q[tail-1]) * getdown(q[tail-1],q[tail-2]) <= getup(q[tail-1],q[tail-2]) * getdown(j,q[tail-1]))
				tail--;
			q[tail++] = j;
		}
		printf("%I64d\n",dp[n]);
	}
	return 0;
}


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