bzoj 1563: [NOI2009]诗人小G

学习了一下决策单调优化……实际上就是奥妙重重的双向队列啦……队列里维护决策的位置以及该决策最优的范围。

不停弹出队头的元素直到当前位置在队头元素最优的范围内。

每次把当前决策插入队尾,并弹出没它优的答案……

然后就是\(O(nlogn)\)的了

#include <bits/stdc++.h>
using namespace std;
#define N 200000
#define LL long long 
#define LD long double
 
int T;
int n, l, p;
int ai[N], sum[N];
LD F[N];
struct node 
{
    int fs, lb, rb;
};
node Q[N]; int fr, tl;
LD powi(LL a, LL b)
{
    LD c = 1;
    while (b --) c *= a;
    return c;
}
LD get(int a, int b)
{
    return F[a] + powi(abs((sum[b] - sum[a] + b - a - 1) - l), p);
}
int main()
{
    //freopen("A.in", "r", stdin);
    scanf("%d", &T);
    while (T --)
    {
        scanf("%d%d%d", &n, &l, &p);
        for (int i = 1; i <= n; ++ i)
        {
            char ch[40];
            scanf("%s", ch);
            sum[i] = sum[i - 1] + strlen(ch);
        }
        Q[0] = ((node){0, 1, n});
        fr = 0; tl = 1;
        for (int i = 1; i <= n; ++ i)
        {
            while (Q[fr].rb < i) Q[fr ++] = ((node){0, 1, n});
            F[i] = get(Q[fr].fs, i);
            while (get(i, Q[tl - 1].lb) < get(Q[tl - 1].fs, Q[tl - 1].lb))
                Q[-- tl] = ((node){0, 1, n});
            {
                int l = Q[tl - 1].lb, r = Q[tl - 1].rb;     
                while (l < r)
                {
                    int md = (l + r + 1) / 2;
                    if (get(i, md) < get(Q[tl - 1].fs, md)) r = md - 1;
                    else l = md;
                }
                if (l >= n) continue;
                Q[tl - 1].rb = l;
                Q[tl ++] = ((node){i, l + 1, n});
            }
        }
        if (F[n] > 1000000000000000000ll) puts("Too hard to arrange");
        else printf("%lld\n", (LL)(F[n] + 0.5));
        puts("--------------------");
    }
}

 

posted @ 2017-01-13 19:29  AwD!  阅读(632)  评论(0编辑  收藏  举报