BZOJ1563 NOI2009 诗人小G【决策单调性优化DP】
因为是图片题就懒得挂了
简要题意:有n个串,拼接两个串需要加一个空格,给你l和p,问你拼接后每个串的总长减l的绝对值的p次方的最小值
首先打表发现一下这题是决策单调的对于所有数据都成立就当他一定成立了
然后网上有神仙用四边形不等式证明了这个东西LINK
我就懒得不会证明了
然后考虑用一个双向的队列维护出每个决策点对应的单调区间
然后保证所有区间一定是连续的
就构成了所有dp的转移区间
其实和bzoj2216非常像
代码都差不多,直接维护就可以了
最后上DP式子:
dp[i] = dp[x] + fast_pow(s[y] - s[x] + y - x - 1 - L, P)
//Author: dream_maker
#include<bits/stdc++.h>
using namespace std;
//----------------------------------------------
//typename
typedef long long ll;
typedef long double ld;
//convenient for
#define for_up(a, b, c) for (int a = b; a <= c; ++a)
#define for_down(a, b, c) for (int a = b; a >= c; --a)
#define for_vector(a, b) for (int a = 0; a < (signed)b.size(); ++a)
//inf of different typename
const int INF_of_int = 1e9;
const ll INF_of_ll = 1e18;
//fast read and write
template <typename T>
void Read(T &x) {
bool w = 1;x = 0;
char c = getchar();
while (!isdigit(c) && c != '-') c = getchar();
if (c == '-') w = 0, c = getchar();
while (isdigit(c)) {
x = (x<<1) + (x<<3) + c -'0';
c = getchar();
}
if (!w) x = -x;
}
template <typename T>
void Write(T x) {
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) Write(x / 10);
putchar(x % 10 + '0');
}
//----------------------------------------------
const int N = 1e5 + 10;
struct Node{int l, r, pos;}p[N];
ld dp[N];
int n, L, P;
int s[N];
char c[N];
ld fast_pow(ld a, int b) {
ld ans = 1.0;
if (a < 0) a = - a;
while (b) {
if (b & 1) ans = ans * a;
b >>= 1;
a = a * a;
}
return ans;
}
ld calc(int x, int y) {
return dp[x] + fast_pow(s[y] - s[x] + y - x - 1 - L, P);
}
int find(Node x, int t) {
int l = x.l, r = x.r, ans = r + 1;
while (l <= r) {
int mid = (l + r) >> 1;
if (calc(x.pos, mid) >= calc(t, mid)) r = mid - 1, ans = mid;
else l = mid + 1;
}
return ans;
}
void solve() {
Read(n), Read(L), Read(P);
for_up(i, 1, n) {
scanf("%s", c + 1);
int len = strlen(c + 1);
s[i] = s[i - 1] + len;
}
int l = 1, r = 1;
p[1] = (Node) {0, n, 0};
for_up(i, 1, n) {
if (l <= r && ++p[l].l > p[l].r) ++l;
dp[i] = calc(p[l].pos, i);
if (l > r || calc(i, n) <= calc(p[r].pos, n)) {
while (l <= r && calc(p[r].pos, p[r].l) >= calc(i, p[r].l)) --r;
int now = (l > r) ? i : find(p[r], i);
if (l <= r) p[r].r = now - 1;
p[++r] = (Node) {now, n, i};
}
}
if (dp[n] > 1e18)printf("Too hard to arrange");
else Write((ll)dp[n]);
printf("\n--------------------\n");
}
int main() {
int T;Read(T);
while (T--) solve();
return 0;
}