Subsequence (二分)【POJ】-3061

来源:互联网 发布:怎样手机域名保护 编辑:程序博客网 时间:2024/05/17 09:26

点击打开链接

Subsequence(子序列)
Time Limit: 1000MS Memory Limit: 65536KTotal 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

210 155 1 3 5 10 7 4 9 2 85 111 2 3 4 5

Sample Output

23

Source

Southeastern Europe 2006

题意:大意就是  编写一个程序来查找序列中连续元素的子序列的最小长度,其总和大于或等于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 的 下标 (位置) => posans=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; 点击打开链接


原创粉丝点击