解题思路
尺取法
中文题意:给定1e5个以内整数,问连续子序列和大于等于S的最小区间长度是多少。
区间和可以用前缀和O1表示,那么就是如何枚举区间的问题,如果枚举长度,枚举起点时间是会
的。
那么雨巨在算法课介绍了一种尺取法的办法,也就是拿一把尺子一样的,如果当前区间和不够m那么一定要把区间长度增大,如果区间和大于等于m了,试试把左端点减小,因为要找到区间最小。能小就小点,注意要保证区间和大于等于m。
#include <cstdio>
#include <cstring>
#include <algorithm>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
using namespace std;
#define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
typedef long long ll;
const ll MOD = 1e9 + 7;
inline ll read() { ll s = 0, w = 1; char ch = getchar(); while (ch < 48 || ch > 57) { if (ch == '-') w = -1; ch = getchar(); } while (ch >= 48 && ch <= 57) s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar(); return s * w; }
inline void write(ll x) { if (!x) { putchar('0'); return; } char F[200]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-'); int cnt = 0; while (tmp > 0) { F[cnt++] = tmp % 10 + '0'; tmp /= 10; } while (cnt > 0)putchar(F[--cnt]); }
inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; b >>= 1; a *= a; } return ans; } ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; }
inline int lowbit(int x) { return x & (-x); }
const int N = 1e5 + 7;
const int INF = 0x3f3f3f3f;
int a[N];
int main() {
int T = read();
while (T--) {
memset(a, 0, sizeof(a));
int n = read(), m = read();
for (int i = 1; i <= n; ++i) a[i] = read(), a[i] += a[i - 1];
int l = 0, r = 1, ans = INF;
while (r <= n) {
if (a[r] - a[l] < m) ++r;
else {
while (a[r] - a[l] >= m) ++l;
ans = min(ans, r - l + 1);
}
}
if (ans == INF) puts("0");
else write(ans), putchar(10);
}
return 0;
}

京公网安备 11010502036488号