【POJ 1821】Fence

【原题题面】传送门

【题解大意】

当两个决策k1<k2且 f[i-1,k1] - p*k1 <= f[i-1,k2]-p*k2,那么此时k1就是无用决策。

可以用单调队列优化。

需要支持的操作:

1.当j变大时,b把小于j-L的决策出队;

2.有新的决策入队时,在队尾检查f[i-1,k]的单调性,把无用决策从队尾直接出队,然后把新决策入队。

【code】

【POJ 1821】Fence
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>    
using namespace std;
#define ll long long 
#define File "fence"
inline void file(){
    freopen(File".in","r",stdin);
    freopen(File".out","w",stdout);
} 
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<<1) + (x<<3) + ch-'0'; ch = getchar();}
    return x*f;
}
const int mxn = 16000 + 10;
const int mxk = 105;
int n,k;

struct P{
    int l,v,s;
}p[mxk];
inline bool cmp(P t1,P t2){
    return t1.s < t2.s;
}

int q[mxn];
int f[mxk][mxn];
inline int Calc(int i,int j){
    return f[i-1][j] - p[i].v*j;
}

int main(){
    file();
    n = read(),k = read();
    for(int i = 1;i <= k; ++i) 
        p[i] = (P){read(),read(),read()};

    sort(p+1,p+k+1,cmp);

    int l(1),r(0);    
    for(int i = 1;i <= k; ++i){
        l = 1,r = 0;
        for(int j = max(p[i].s-p[i].l,0);j <= p[i].s-1; ++j){
            while(l <= r && Calc(i,q[r]) <= Calc(i,j)) --r;
            q[++r] = j;//新的决策从队尾入队 
        }
        for(int j = 1;j <= n; ++j){
            f[i][j] = max(f[i-1][j],f[i][j-1]);
            if(j >= p[i].s){
                while(l <= r && q[l] < j - p[i].l) ++l;
                if(l <= r) f[i][j] = max(f[i][j],Calc(i,q[l]) + p[i].v*j);
            }
        }
    }
    printf("%d\n",f[k][n]);    
    return 0;
}
View Code
上一篇:[codeforces1221D] Make The Fence Great Again dp


下一篇:【POJ1821】Fence