Problem

给定一个长度为n的数字串,从中选取k个不重叠的子串(可以少选),将每个串求和si
求max|s1 - s2| + |s2 - s3| + ... + |sk - 1 - sk|(n <= 30000, k <= min(n, 200))

Solution

绝对值后的和,只和峰值和谷值的那些值有关(所以我们可以贪心峰值和谷值尽量多)
用f[i][j][k]表示前i个,分成j段,这个值在哪里(用k=0表示在谷值,k=1表示在谷值到峰值之间,k=2表示在峰值,k=3表示在峰值到谷值之间)
f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j - 1][3]) - flag * x;
f[i][j][1] = max(f[i - 1][j][1], f[i][j][0]);
f[i][j][2] = max(f[i - 1][j][2], f[i - 1][j - 1][1]) + flag * x;
f[i][j][3] = max(f[i - 1][j][3], f[i][j][2]);
flag是什么呢?如果是第一个或者最后一个计算时只算一次,中间的都算两次
然后实际中,全部是峰值和谷值是不一定现实的,所以中间部分还要加上转移:
f[i][j][1] = max(f[i][j][1], f[i - 1][j - 1][1]);
f[i][j][3] = max(f[i][j][3], f[i - 1][j - 1][3]);

Notice

注意第一个或最后一个和其他地方是不一样的。

Code

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define sqz main
#define ll long long
#define reg register int
#define rep(i, a, b) for (reg i = a; i <= b; i++)
#define per(i, a, b) for (reg i = a; i >= b; i--)
#define travel(i, u) for (reg i = head[u]; i; i = edge[i].next)
const int INF = 1e9, N = 30005, K = 205;
const double eps = 1e-6, phi = acos(-1.0);
ll mod(ll a, ll b) {if (a >= b || a < 0) a %= b; if (a < 0) a += b; return a;}
ll read(){ ll x = 0; int zf = 1; char ch; while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
if (ch == '-') zf = -1, ch = getchar(); while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;}
void write(ll y) { if (y < 0) putchar('-'), y = -y; if (y > 9) write(y / 10); putchar(y % 10 + '0');}
int f[N][K][4];
int sqz()
{
	int n = read(), k = read();
	rep(i, 1, k)
		rep(j, 0, 3) f[0][i][j] = -INF;
	rep(i, 1, n)
	{
		int x = read();
		rep(j, 1, k)
		{
			int flag = 2 - (j == 1 || j == k);
			f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j - 1][3]) - flag * x;
			f[i][j][1] = max(f[i - 1][j][1], f[i][j][0]);
			f[i][j][2] = max(f[i - 1][j][2], f[i - 1][j - 1][1]) + flag * x;
			f[i][j][3] = max(f[i - 1][j][3], f[i][j][2]);
			if (flag - 1)
			{
				f[i][j][1] = max(f[i][j][1], f[i - 1][j - 1][1]);
				f[i][j][3] = max(f[i][j][3], f[i - 1][j - 1][3]);
			}
		}
	}
	printf("%d\n", max(f[n][k][1], f[n][k][3]));
}
posted on 2017-10-17 14:38  WizardCowboy  阅读(109)  评论(0编辑  收藏  举报