BZOJ1044: [HAOI2008]木棍分割(dp 單調佇列)

自為風月馬前卒發表於2018-10-09

題意

題目連結

Sol

比較套路的一個題。

第一問二分答案check一下

第二問設(f[i][j])表示前(i)個數,切了(j)段的方案數,單調佇列優化一下。

轉移的時候只需要保證當前段的長度小於最大限度即可。

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 50001, mod = 10007;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < `0` || c > `9`) {if(c == `-`)f =- 1; c = getchar();}
    while(c >= `0` && c <= `9`) x = x * 10 + c - `0`, c = getchar();
    return x * f;
}
int N, M, a[MAXN], sum[MAXN];
int check(int val) {
    int tot = 0, pre = 0;
    for(int i = 1; i <= N; i++) {
        if(sum[i] - sum[pre] > val) {
            if((sum[i - 1] - sum[pre] <= val) && a[i] <= val) tot++, pre = i - 1;
            else return 0;
        }
    }
    return tot <= M;
}
int solve1() {
    int l = 0, r = sum[N], ans;//二分最大長度
    while(l <= r) {
        int mid = l + r >> 1;
        if(check(mid)) ans = mid, r = mid - 1;
        else l = mid + 1;
    }
    return printf("%d ", ans), ans;
}
int add(int x, int y) {
    if(x + y < 0) return x + y + mod;
    else return (x + y > mod ? x + y - mod : x + y);
}
int solve2(int mx) {
    static int f[MAXN], g[MAXN], q[MAXN], ans = 0;
    // f[0][0] = 1;
    for(int i = 1; i <= N; i++) g[i] = (sum[i] <= mx);
    for(int j = 1; j <= M; j++) {
        for(int i = 1, h = 1, t = 0, s = 0; i <= N; i++) {
            while(h <= t && (sum[i] - sum[q[h]] > mx)) s = add(s, -g[q[h++]]);
            q[++t] = i;
            f[i] = s; s = add(s, g[i]);
           /* for(int k = i - 1; k >= 1; k--) {
                if(sum[i] - sum[k] <= mx) (f[i][j] += f[k][j - 1]) %= mod;
                else break;
            }*/
        }
        ans = add(ans, f[N]);
        memcpy(g, f, sizeof(g));
    }
    return ans % mod;
}
int main() {
//  freopen("10.in", "r", stdin);
    N = read(); M = read();
    for(int i = 1; i <= N; i++) a[i] = read(), sum[i] = sum[i - 1] + a[i];
    printf("%d", solve2(solve1()));
}

相關文章