1. 程式人生 > >P2511 [HAOI2008]木棍分割

P2511 [HAOI2008]木棍分割

Description

有n根木棍, 第i根木棍的長度為Li,n根木棍依次連結了一起, 總共有n-1個連線處. 現在允許你最多砍斷m個連線處, 砍完後n根木棍被分成了很多段,要求滿足總長度最大的一段長度最小, 並且輸出有多少種砍的方法使得總長度最大的一段長度最小. 並將結果mod 10007。。。

Solution

二分答案+動態規劃

Code

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

const int mod = 10007;
const int N = 50005;
int l[N];

bool judge(int lim, int n, int m) {
    int used = 0, sig = 0;
    for (int i = 1; i <= n; i += 1) {
        if (sig + l[i] <= lim) sig += l[i];
        else sig = l[i], used += 1;
    }
    return used <= m;
}

int s[N], p[N];
int f1[N], f2[N];
int get(int L, int n, int m) {
    for (int i = 1; i <= n; i += 1)
        s[i] = s[i - 1] + l[i];
    for (int i = 1; i <= n; i += 1)
        p[i] = std:: lower_bound(s, s + n + 1, s[i] - L) - s;
    int *f = f1, *g = f2;
    for (int i = 0; i <= n; i += 1) g[i] = 1;
    int res = 0;
    for (int i = 1; i <= m + 1; i += 1) {
        for (int j = 1; j <= n; j += 1) {
            f[j] = (g[j - 1] - g[p[j] - 1]) % mod;
        }
        res = (res + f[n]) % mod;
        f[0] = 0;
        for (int j = 1; j <= n; j += 1)
            f[j] = (f[j - 1] + f[j]) % mod;
        std:: swap(f, g);
    }
    return (res + mod) % mod;
}

int main () {
    int n, m, Mx = 0, Ma = 0;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i += 1)
        scanf("%d", &l[i]), Mx += l[i], Ma = std:: max(Ma, l[i]);
    int l = Ma, r = Mx, mid;
    while (l <= r) {
        mid = l + r >> 1;
        if (judge(mid, n, m)) r = mid - 1;
        else l = mid + 1;
    }
    printf("%d ", l);
    printf("%d\n", get(l, n, m));
    return 0;
}