304. 诗人小G(算法竞赛进阶指南,一维线型 DP 的四边形不等式优化)
程序员文章站
2022-04-01 18:42:04
...
一.题目链接:
诗人小G
二.题目大意:
啦啦啦~
三.分析:
做了好久,终于想明白了(在想peach)
没错,就是没有分析!
小吐槽:答案必须用 long double 存储,太傻吊了.
四.代码实现:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M = (int)1e5;
int N, L, P;
char s[35];
int sum[M + 5];
struct node
{
int j, l, r;
}q[M + 5];
int l, r;
long double f[M + 5];
int bs1(int i)
{
int l = ::l, r = ::r, mid;
while(l < r)
{
mid = (l + r) >> 1;
if(q[mid].r >= i)
r = mid;
else
l = mid + 1;
}
return q[r].j;
}
long double cal(int i, int j)
{
long double sum = 1.0, num = abs(::sum[i] - ::sum[j] + i - j - 1 - L);
for(int i = 0; i < P; ++i) sum *= num;
return f[j] + sum;
}
int bs2(int i, int j, int l, int r)
{
int mid;
while(l < r)
{
mid = (l + r) >> 1;
if(cal(mid, i) > cal(mid, j))
l = mid + 1;
else
r = mid;
}
return r;
}
void ins(int i)
{
int pos = -1;
while(l <= r)
{
if(cal(q[r].l, i) <= cal(q[r].l, q[r].j))
pos = q[r--].l;
else
{
if(cal(q[r].r, i) < cal(q[r].r, q[r].j))
{
pos = bs2(i, q[r].j, q[r].l, q[r].r);
q[r].r = pos - 1;
}
break;
}
}
if(~pos)
{
q[++r].j = i;
q[r].l = pos;
q[r].r = N;
}
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%d %d %d", &N, &L, &P);
for(int i = 1; i <= N; ++i)
{
scanf("%s", s);
sum[i] = sum[i - 1] + strlen(s);
}
l = 1, r = 0;
q[++r].j = 0, q[r].l = 1, q[r].r = N;
memset(f, 0, sizeof(f));
for(int i = 1; i <= N; ++i)
{
int j = bs1(i);
f[i] = cal(i, j);
while(l <= r && q[l].r <= i) ++l;
q[l].l = i + 1;
ins(i);
}
if(f[N] > (ll)1e18) printf("Too hard to arrange\n");
else printf("%lld\n", (ll)f[N]);
for(int i = 0; i < 20; ++i) putchar('-');
puts("");
}
return 0;
}
下一篇: 求最多能有多少个点位于同一直线上