Subsequence(子序列)
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15912 | Accepted: 6730 |
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
题意:大意就是 编写一个程序来查找序列中连续元素的子序列的最小长度,其总和大于或等于s。
代码:
#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
int a[100005];
int main()
{
int t;
cin >> t;
while(t--)
{
int n,s;
cin >> n >> s ;
cin >> a[0];
for(int i=1;i<n;i++)
{
cin >> a[i];
a[i]+=a[i-1]; //i位置之前所有数的和存到a[i]里面
}
if(a[n-1]<s)
{
// cout >> >> endl;
printf("0\n");
continue;
}
int pos,ans=n;
for(int i=n-1;i>=0;i--)
{
if(a[i]<s)
break;
pos=upper_bound(a,a+n,a[i]-s)-a; //找a[i]-s 的 i 的 下标 (位置) => pos
ans=min(ans,i-pos+1); //a[i]的当前位置减去 pos 再加 1 ,即最短序列的长度
}
cout << ans << endl;
}
return 0;
}
/*
1 2 3 4 5 5 5 6 7 10
让 k=5
upper_bound(begin(),end()+1,k); 找 >k 的
lower_bound(begin(),end()+1,k); 找 >=k 的
*/
了解
pos=upper_bound(a,a+n,a[i]-s)-a; 点击打开链接