Subsequence POJ - 3061 (尺取模板)
题意:给定长度n的整数数组,以及整数s,求出总和不小于s的子数组长度的最小值。
Input
第一行输入n和s,第二行输入n个正整数。
Output
找到满足要求的子数组的最小长度,如果没有,输出0。
Sample Input
2
10 15
5 1 3 5 10 7 4 9 2 8
5 11
1 2 3 4 5
Sample Output
2
3
代码;
#include <iostream> #include <algorithm> #include <string.h> #include <cstdio> #include <string> #include <cmath> #include <vector> #include <stack> #include <queue> #include <stack> #include <list> #include <map> #include <set> //#include <unordered_map> #define Fbo friend bool operator < (node a, node b) #define mem(a, b) memset(a, b, sizeof(a)) #define FOR(a, b, c) for (int a = b; a <= c; a++) #define RFOR(a, b, c) for (int a = b; a >= c; a--) #define off ios::sync_with_stdio(0) #define sc(a) scanf("%d",&a) bool check1(int a) { return (a & (a - 1)) == 0 ? true : false; } using namespace std; typedef pair<int, int> pii; typedef long long ll; const int INF = 0x3f3f3f3f;//1e10 const int mod = 1e9 + 7; const int Maxn = 2e5+9; const double pi = acos(-1.0); const double eps = 1e-8; int a[Maxn]; int main() { int t; cin >> t; while (t--) { int n, s; cin >> n >> s; FOR(i, 1, n)sc(a[i]); int i = 1, j = 1, sum = 0, ans = INF; while (1) { while (j <= n && sum < s) { sum += a[j++]; } if (sum < s) break; ans = min(ans, j - i); sum -= a[i++]; } if (ans == INF)printf("0\n"); else printf("%d\n", ans); } }