题解 P3580 【[POI2014]ZAL-Freight】
单调队列优化DP
对于这道题,我们考虑最优的情况是什么,一定是一波过来,一波回去;再一波过来,一波回去。
那么我们来设计一下DP方程。。
设
转移是
考虑拆掉
当
另一种情况
完整代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#define ll long long
using namespace std;
const int N = 1000005;
inline int read()
{
int x = 0 , f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9') {x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar();}
return x * f;
}
int n , S , last , ans , head = 1 , tail;
int q[N << 1];
ll f[N] , a[N];
int main()
{
// freopen("c.in","r",stdin);
// freopen("c.out","w",stdout);
n = read(); S = read(); memset(f,0x3f,sizeof f);
for(int i = 1;i <= n;i ++) a[i] = (long long)read();
sort(a+1,a+1+n); a[0] = -1;
for(int i = 1;i <= n;i ++) a[i] = max(a[i],a[i-1] + 1);
for(int i = 1;i <= n;i ++)
{
while(head <= tail && f[q[head]] - q[head] < a[i] - i + 1) head ++;
f[i] = min(f[i],a[i] + 2 * S + i - q[head-1] - 1);
f[i] = min(f[i],f[q[head]] + 2 * (S + i - q[head] - 1));
while(head <= tail && f[q[tail]] - 2 * q[tail] > f[i] - 2 * i) tail --;
q[++tail] = i;
}
printf("%lld\n",f[n]);
fclose(stdin);
fclose(stdout);
return 0;
}