题目
Subsequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 16652 | Accepted: 7073 |
Description
A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.
Input
The first line is the number of test cases. For each test case the program has to read the numbers N and S, separated by an interval, from the first line. The numbers of the sequence are given in the second line of the test case, separated by intervals. The input will finish with the end of file.
Output
For each the case the program has to print the result on separate line of the output file.if no answer, print 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
Source
心得:
数组sum[i]表示a[i]的前i-1项和,sum[0]=0,(i,R]内
相邻数的和即为sum[R]-sum[i]。
以
5 11
1 2 3 4 5 中i=0 为例,显示二分法过程 L=0 m=2 R=5
| | |
m=(R+L)/2; m=2; sum[m]-sum[i]<S;L=m;
L=2 m=3 R=5
| | |
m=(R+L)/2; m=3; sum[m]-sum[i]<S;L=m;
L=3 m=4 R=5
| | |
此时R-L=1;不符合条件,退出循环,R=5,长度为R-i=5;
代码<c语言>
#include<stdio.h>
int a[100005],sum[100005];
int find(int L,int R,int S){//范围(L,R],S用来比较的数,二分法查找最先大于等于S的数
int m,i;
i=L;
sum[0]=0;
while(R-L>=2){
m=(R+L)/2;
if(sum[m]-sum[i]<S)//(i,m]
L=m;
else
R=m;
}
return R;
}
int main(){
int i,j,n,N,S,R,min;
scanf("%d",&n);//测试的次数
while(n--){
scanf("%d%d",&N,&S);//N个整数,S是要大于等于的数
min=N+1;
for(i=0;i<N;i++){
scanf("%d",&a[i]);
sum[i+1]=sum[i]+a[i];//sum[i]记录前i-1项和,令sum[0]=0
}
if(sum[N]<S){//不会大于等于S,反之,一定存在大于等于S
printf("%d\n",0);
continue;
int a[100005],sum[100005];
int find(int L,int R,int S){//范围(L,R],S用来比较的数,二分法查找最先大于等于S的数
int m,i;
i=L;
sum[0]=0;
while(R-L>=2){
m=(R+L)/2;
if(sum[m]-sum[i]<S)//(i,m]
L=m;
else
R=m;
}
return R;
}
int main(){
int i,j,n,N,S,R,min;
scanf("%d",&n);//测试的次数
while(n--){
scanf("%d%d",&N,&S);//N个整数,S是要大于等于的数
min=N+1;
for(i=0;i<N;i++){
scanf("%d",&a[i]);
sum[i+1]=sum[i]+a[i];//sum[i]记录前i-1项和,令sum[0]=0
}
if(sum[N]<S){//不会大于等于S,反之,一定存在大于等于S
printf("%d\n",0);
continue;
}//continue退出当前循环,开始下一次循环
for(i=0;i<N&&sum[N]-sum[i]>=S;i++){//如果不满足这个条件 sum[N]-sum[i]>=S,就没必要查找
R=find(i,N,S);//调用这个函数,在 区间(i,N]内用二分法查找最先大于等于S的 sum[R]-sum[i]
min=min<(R-i)?min:(R-i);//R-i为区间的距离,即大于等于S的相邻数的个数
}
printf("%d\n",min);
}
return 0;
}
for(i=0;i<N&&sum[N]-sum[i]>=S;i++){//如果不满足这个条件 sum[N]-sum[i]>=S,就没必要查找
R=find(i,N,S);//调用这个函数,在 区间(i,N]内用二分法查找最先大于等于S的 sum[R]-sum[i]
min=min<(R-i)?min:(R-i);//R-i为区间的距离,即大于等于S的相邻数的个数
}
printf("%d\n",min);
}
return 0;
}
AC情况: