题意:给定N个数,求和大于等于S的最短连续子序列的长度。
分析:滑动窗口即可。两种写法。
1、
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
if(fabs(a - b) < eps) return 0;
return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 100000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int a[MAXN];
int main(){
int T;
scanf("%d", &T);
while(T--){
int N, S;
scanf("%d%d", &N, &S);
int tot = 0;
for(int i = 0; i < N; ++i){
scanf("%d", &a[i]);
tot += a[i];
}
if(tot < S){
printf("0\n");
continue;
}
int st = 0, et = 0;
int sum = 0;
int cnt = 0x7f7f7f7f;
while(et < N){
while(et < N && sum + a[et] < S){
sum += a[et];
++et;
}
cnt = min(cnt, et - st + 1);
sum -= a[st];
++st;
}
printf("%d\n", cnt);
}
return 0;
}
2、
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
if(fabs(a - b) < eps) return 0;
return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 100000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int a[MAXN];
int main(){
int T;
scanf("%d", &T);
while(T--){
int N, S;
scanf("%d%d", &N, &S);
int tot = 0;
for(int i = 0; i < N; ++i){
scanf("%d", &a[i]);
tot += a[i];
}
if(tot < S){
printf("0\n");
continue;
}
int st = 0, et = 0;
int sum = 0;
int cnt = 0x7f7f7f7f;
for(int i = 0; i < N; ++i){
sum += a[i];
while(sum - a[st] >= S){
sum -= a[st];
++st;
}
if(sum >= S){
cnt = min(cnt, i - st + 1);
sum -= a[st];
++st;
}
}
printf("%d\n", cnt);
}
return 0;
}