长度最小的子数组 wa90分

#include <bits/stdc++.h>

#define ll long long

using namespace std; 
 
int f(ll s, vector<ll>& nums){ 
    ll n=nums.size();  
    int left=0; 
    ll sum=0; 
    int minLen=INT_MAX; 
    for (int right=0; right<n; right++) { 
        sum+=nums[right];
        while (sum>=s) {
            minLen=min(minLen, right - left + 1); 
            sum-=nums[left]; 
            left++; 
        }
    } 
 
    return (minLen==INT_MAX)?0:minLen; 
} 
 
int main() { 
    ll T; 
    cin >> T; 
 
    while (T--) { 
        ll n, s; 
        cin >> n >> s; 
        vector<ll> nums(n); 
        for (ll i=0; i<n; ++i) { 
            cin >> nums[i]; 
        }
        cout << f(s, nums) << endl; 
    } 
 
    return 0; 
} 
1 个赞

1 个赞
#include <bits/stdc++.h>

#define ll long long

using namespace std; 
 
int f(ll s, vector<ll>& nums){ 
    ll n=nums.size();  
    int left=0; 
    ll sum=0; 
    int minLen=INT_MAX; 
    for (int right=0; right<n; right++) { 
        sum+=nums[right];
        while (left<=n&&right<n) {
            if(sum<s){
                right++;
                sum+=nums[right];
            }
            else{
                minLen=min(minLen, right - left + 1); 
                sum-=nums[left]; 
                left++;
            }
        }
    } 
 
    return (minLen==INT_MAX)?0:minLen; 
} 
 
int main() { 
    ll T; 
    cin >> T; 
 
    while (T--) { 
        ll n, s; 
        cin >> n >> s; 
        vector<ll> nums(n); 
        for (ll i=0; i<n; ++i) { 
            cin >> nums[i]; 
        }
        cout << f(s, nums) << endl; 
    } 
 
    return 0; 
} 

还是wa90

1 个赞

写反了吧

1 个赞
#include <bits/stdc++.h>

#define ll long long

using namespace std; 
 
int main(){
  int t;
  cin >> t;
  while(t--){
    ll n,s,l=1,r=1,now,ans=1e9;
    cin >> n >> s;
    ll a[n+1];
    for(int i=0;i<n;i++){
      cin >> a[i];
    }
    now=a[1];
    if(s==0){
      cout << 1 << endl;
      continue;
    }
    while(l<=n&&r<=n){
      if(now<s){
        r++;
        now+=a[r];
      }
      else{
        ans=min(ans,r-l+1);
        now-=a[l];
        l++;
      }
    }
    if(ans==1e9){
      cout << 0 << endl;
    }
    else{
      cout << ans << endl;
    }
  }
  return 0;
} 

0 pts

1 个赞

now=a[1]?

1 个赞

??

1 个赞