#include <iostream> //nlogn复杂度的写法 #include <cstdio> #include <algorithm> using namespace std; typedef long long ll; const int INF = 0x3f3f3f3f; const int moder = 1e9 + 7; const int maxn = 100005; int a[maxn]; int main() { int t; cin >> t; while(t--) { int n,s; scanf("%d%d",&n,&s); for(int i=1;i <= n;i++) scanf("%d",&a[i]); for(int i=2;i <= n;i++) { a[i] = a[i] + a[i-1]; } if(a[n] < s) printf("0 "); else { int res = n; for(int i=1;a[n]-a[i] >= s;i++) { int t = lower_bound(a+1,a+n+1,s+a[i]) - a; // - a 非 - a - 1 res = min(res,t-i); } printf("%d ",res); } } return 0; } /*2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5 */
O(n)复杂度的写法
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; typedef long long ll; const int INF = 0x3f3f3f3f; const int moder = 1e9 + 7; const int maxn = 100005; int a[maxn]; int main() { int t; cin >> t; while(t--) { int n,s; scanf("%d%d",&n,&s); for(int i=1;i <= n;i++) scanf("%d",&a[i]); int i=1,j=1; int sum=0; int res = n+1; for(;;) { while(i <= n && sum < s) { sum += a[i]; i++; } if(sum < s) break; res = min(res,i-j); sum = sum - a[j]; j++; } if(res > n) res = 0; printf("%d ",res); } return 0; } /*2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5 */
——