Subsequence (二分)【POJ】-3061

點擊打開鏈接

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; 點擊打開鏈接


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章