o o o o o o o o o o o o o o o o o o /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F\ /F/ \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \
o o o | o o o o | o o o o o o | o o o o o /F\ /F\ /F\ | /F\ /F\ /F\ /F\ | /F\ /F\ /F\ /F\ /F\ /F\ | /F\ /F\ /F\ /F\ /F/ \ / \ / \ | / \ / \ / \ / \ | / \ / \ / \ / \ / \ / \ | / \ / \ / \ / \ / \
, b0 = 0 and 1 <= k <= M, if there are M groups in total. Note that M can equal to 1.2 5 2 1 4 3 2 5 5 2 5 4 3 2 1
Case #1: 31 Case #2: No solution
#include <map>
#include <set>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int n, d;
int arr[N];
__int64 dp[N];
struct data
{
int x, pos;
}sorting[N];
struct node
{
int l, r;
__int64 val;
}tree[N << 2];
int cmp(data a, data b)
{
if (a.x != b.x)
{
return a.x < b.x;
}
return a.pos > b.pos;
}
void build(int p, int l, int r)
{
tree[p].l = l;
tree[p].r = r;
tree[p].val = -1;
if (l == r)
{
return;
}
int mid = (l + r) >> 1;
build(p << 1, l, mid);
build(p << 1 | 1, mid + 1, r);
}
void update(int p, int pos, __int64 val)
{
if (tree[p].l == tree[p].r)
{
tree[p].val = val;
return;
}
int mid = (tree[p].l + tree[p].r) >> 1;
if (pos <= mid)
{
update(p << 1, pos, val);
}
else
{
update(p << 1 | 1, pos, val);
}
tree[p].val = max(tree[p << 1].val, tree[p << 1 | 1].val);
}
__int64 query(int p, int l, int r)
{
if (l <= tree[p].l && r >= tree[p].r)
{
return tree[p].val;
}
int mid = (tree[p].l + tree[p].r) >> 1;
if (r <= mid)
{
return query(p << 1, l, r);
}
else if (l > mid)
{
return query(p << 1 | 1, l, r);
}
else
{
return max(query(p << 1, l, mid), query(p << 1 | 1, mid + 1, r));
}
}
int main()
{
int t, icase = 1;
scanf("%d", &t);
while (t--)
{
scanf("%d%d", &n, &d);
memset (dp, -1, sizeof(dp));
arr[0] = 0;
dp[0] = 0;
for (int i = 1; i <= n; ++i)
{
scanf("%d", &arr[i]);
sorting[i].x = arr[i];
sorting[i].pos = i;
}
sort (sorting + 1, sorting + n + 1, cmp);
build(1, 0, n);
update(1, 0, 0);
for (int i = 1; i <= n; ++i)
{
int j = sorting[i].pos;
__int64 cur = query(1, max(0, j - d), j - 1);
if (cur >= 0)
{
dp[j] = cur + (__int64)arr[j] * arr[j];
update(1, j, dp[j] - arr[j]);
}
}
printf("Case #%d: ", icase++);
if (dp[n] <= 0)
{
printf("No solution\n");
}
else
{
printf("%I64d\n", dp[n]);
}
}
return 0;
}原文:http://blog.csdn.net/guard_mine/article/details/41758633