bzoj2600 [Ioi2011]ricehub 双指针

题目传送门

https://lydsy.com/JudgeOnline/problem.php?id=2600

题解

随便写一个比较简单的 two pointers 练习题。

首先答案肯定是一个原序列上的区间。然后一个区间的费用——显然选择的点应该是这个区间的中位数(初中数学)。

然后一个区间的费用肯定比其子区间费用要大。

所以可以直接 two-pointers 来做。


时间复杂度 \(O(n)\)

#include<bits/stdc++.h>

#define fec(i, x, y) (int i = head[x], y = g[i].to; i; i = g[i].ne, y = g[i].to)
#define dbg(...) fprintf(stderr, __VA_ARGS__)
#define File(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)
#define fi first
#define se second
#define pb push_back

template<typename A, typename B> inline char smax(A &a, const B &b) {return a < b ? a = b, 1 : 0;}
template<typename A, typename B> inline char smin(A &a, const B &b) {return b < a ? a = b, 1 : 0;}

typedef long long ll; typedef unsigned long long ull; typedef std::pair<int, int> pii;

template<typename I> inline void read(I &x) {
	int f = 0, c;
	while (!isdigit(c = getchar())) c == '-' ? f = 1 : 0;
	x = c & 15;
	while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + (c & 15);
	f ? x = -x : 0;
}

const int N = 100000 + 7;

int n, m;
ll b;
int a[N];
ll s[N];

inline ll get(int l, int r) {
	int mid = (l + r) >> 1;
	return s[r] - s[mid] - (ll)(r - mid) * a[mid] + (ll)(mid - l) * a[mid] - (s[mid - 1] - s[l - 1]);
}

inline void work() {
	int p = 1, ans = 0;
	for (int i = 1; i <= n; ++i) {
		smax(p, i);
		while (p < n && get(i, p + 1) <= b) ++p;
		smax(ans, p - i + 1);
	}
	printf("%d\n", ans);
}

inline void init() {
	read(n), read(m), read(b);
	for (int i = 1; i <= n; ++i) read(a[i]), s[i] = s[i - 1] + a[i];
}

int main() {
#ifdef hzhkk
	freopen("hkk.in", "r", stdin);
#endif
	init();
	work();
	fclose(stdin), fclose(stdout);
	return 0;
}
posted @ 2019-10-31 10:43  hankeke303  阅读(118)  评论(0编辑  收藏  举报