P2627 [USACO11OPEN] Mowing the Lawn G

\(f_i\) 表示对于前 \(i\) 个数,\(i\) 选了, \(g_i\) 表示对于前 \(i\) 个数,\(i\) 没选,\(sum_i=\sum_{j=1}^{i}e_j\) 我们可以列出状态转移方程。

\[\begin{aligned}g_i&=\max\{g_{i-1},f_{i-1}\}\\f_i&=\max\limits_{i-k\le j<i}\{g_j+(sum_i-sum_{j})\}\end{aligned} \]

然后化简一下

\[\begin{aligned}g_i&=\max\{g_{i-1},f_{i-1}\}\\f_i&=\max\limits_{i-k\le j<i}\{g_j-sum_{j}\}+sum_i\end{aligned} \]

对于 \(g\) 直接做,对于 \(f\) 可以用滑动窗口,单调队列来做。

//#define FILE_INPUT
#include <iomanip>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#define int long long
using namespace std;

bool Mbe;

#define rep(i, a, b) for (int i = a, END##i = b; i <= END##i; i++)
#define per(i, a, b) for (int i = a, END##i = b; i >= END##i; i--)
#define DEBUG(x) cerr << #x << " = " << x << '\n'

using LL = long long;
using ULL = unsigned long long;

inline LL read() {
	LL s = 0, fu = 1; char ch = getchar();
	while (ch < '0' || ch > '9') ch == '-' ? fu = -1 : 0, ch = getchar();
	while (ch >= '0' && ch <= '9') s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
	return s * fu;
}

const int Mod = 1e9 + 7;
const int Inf = 0x3f3f3f3f;
const LL InfLL = 0x3f3f3f3f3f3f3f3f;

const int N = 1e5 + 10;
int n, k, a[N], f[N], g[N], sum[N], q[N], hh, tt; // 留个下界 0

void Init() {
}

void Solve() {
	n = read(), k = read();
	rep(i, 1, n) a[i] = read(), sum[i] = a[i] + sum[i - 1];
	rep(i, 1, n) {
		g[i] = max(g[i - 1], f[i - 1]);
		while (hh <= tt && i - k > q[hh]) hh++;
		f[i] = g[q[hh]] - sum[q[hh]] + sum[i];
		while (hh <= tt && g[q[tt]] - sum[q[tt]] < g[i] - sum[i]) tt--;
		q[++tt] = i;
	}
	rep(i, 1, n) printf("%lld %lld\n", f[i], g[i]);
	printf("%lld\n", max(f[n], g[n]));
}

bool Med;

signed main() {
	
#ifdef FILE_INPUT
	freopen("input.in", "r", stdin);
#endif
	
	int T = 1;
//	T = read();
	while (T--) {
		Init();
		Solve();
	}
	
	cerr << "Memory: " << fixed << setprecision(3) << (&Med - &Mbe) / 1048576.0 << " MB\n";
	cerr << "Time: " << fixed << setprecision(3) << 1e3 * clock() / CLOCKS_PER_SEC << " ms\n";
	return 0;
}
posted @ 2025-02-11 19:06  wh2011  阅读(21)  评论(0)    收藏  举报