Binary + prefix and Method
The length of the sub-sequence meeting the condition is between (0, n, sum [x + I]-sum [I] is the sum of the elements whose sequence length is X starting from the I element. Prefix and time that can be counted in O (N)
The value of sum [I. Use the second part to find the minimum length of the sub-sequence that meets the condition.
#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>#include<queue>#include<set>#include<map>#include<vector>#include<cmath>#define ll __int64#define INF 0x3fffffffusing namespace std;int sum[100005];int a[100005];int n,s;bool C(int x){ bool flag=false; for(int i=0;i<n-x;i++) { if(sum[x+i]-sum[i]>=s) { flag=true; break; } } if(flag) return true; else return false;}int solve(){ int l=0,r=n+1; while(r-l>1) { int mid=(l+r)/2; if(C(mid)) r=mid; else l=mid; } return r;}int main(){ int T; //freopen("d:\\Test.txt","r",stdin); cin>>T; while(T--) { cin>>n>>s; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } sum[0]=a[0]; for(int i=1;i<n;i++) { sum[i]=sum[i-1]+a[i]; } if(solve()==n+1) cout<<"0"<<endl; else cout<<solve()<<endl; } return 0;}
Ruler Acquisition Method
(1) set two pointers, S and T, pointing to the first element of the series at the beginning, and sum = 0, Res = 0;
(2) As long as sum <s, an element is added to sum, and T is added to 1;
(3) until sum> = s, update res = min (Res, t-s );
(4) subtract an element from Sum, add s to 1, and execute (2 ).
The above process repeatedly advances the beginning and end of the interval to obtain the minimum interval that meets the conditions.
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int n,m;int a[100005];void solve(){ int res=n+1; int s=0,t=0,sum=0; while(true) { while(t<n&&sum<m) { sum+=a[t++]; } if(sum<m) break; res=min(res,t-s); sum-=a[s++]; } if(res>n) res=0; cout<<res<<endl;}int main(){int T; //freopen("d:\\Test.txt","r",stdin); cin>>T; while(T--) { cin>>n>>m; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } solve(); } return 0;}
Poj3061 subsequence (Binary prefix and method + ruler acquisition)