poj--3061--Subsequence(技巧)

来源:互联网 发布:mcs51单片机数据总线 编辑:程序博客网 时间:2024/06/03 16:28
Subsequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11099 Accepted: 4602

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

2

3

以前做过的一道题,,,现在再刷一遍

题意:给出了n个数,然后求最短的子串,这个字串和大于s,然后输出长度

思路:肯定是不能暴力的,所以我们从头开始加,加到和大于s,然后求该字串的最优,然后再接着加

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;int num[100000 + 10];int main(){int t;cin >> t;while (t--){int n, s;cin >> n >> s;memset(num, 0, sizeof(num));for (int i = 0; i < n; i++)cin >> num[i];int l, r, minn = 0x3f3f3f3f, sum = 0;l = r = 0;//子串通过l--r来限定 bool f = false;while (r < n){sum += num[r++];while (sum >= s)//找到一个之后就取最优 {f = true;//标记有答案 minn = min(minn, r - l);sum -= num[l++];}}if (f)cout << minn << endl;elsecout << 0 << endl;}return 0;}


0 0
原创粉丝点击