ZOJ

来源:互联网 发布:如何导入数据到excel 编辑:程序博客网 时间:2024/06/05 01:27

Subsequence

Time Limit: 1 Second      Memory Limit: 32768 KB

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
题意:给n个数,求最短子序列的和大于s。

解决:从前往后加,大于S就存起来长度,减去前面的数(while很关键),最后输出结果。

细节:可能所有的数加起来都不大于s,输出0.

#include <iostream>#include <cstdio>#include <cstring>#include <bits/stdc++.h>using namespace std;const int INF = 0x3f3f3f;const int maxn = 100000;int t, n, s;int a[maxn + 5];int ans, behind,sum ;int main(){    scanf("%d", &t);    while(t--){        scanf("%d%d", &n, &s);        ans = INF, behind = 0, sum = 0;        for(int i = 0; i < n; i++){            scanf("%d", &a[i]);            sum += a[i];            while(sum >= s){                ans = min(ans, i - behind + 1);                sum -= a[behind++];            }        }        if(ans == INF) cout << 0 << endl;        else            cout << ans << endl;    }}

原创粉丝点击