Subsequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 17085 | Accepted: 7265 |
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
题意:求和>=s的最短子序列长度
解法一:对于每一种取法的区间左端点,二分找到区间右端点,计算区间长度;
复杂度O(nlogn)
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
int m,n,minl;
int s;
int v[100005];
int sum[100005];
int main(int argc, char const *argv[])
{
scanf("%d",&m);
while(m--){
scanf("%d%d",&n,&s);
minl = n;
sum[0] = 0;
for (int i = 0; i < n; ++i) {
scanf("%d",&v[i]);
sum[i+1] = sum[i]+v[i];
}
if(sum[n] < s){printf("0\n");continue;}
for (int i = 0; sum[i]+s <= sum[n]; ++i){
int end = lower_bound(sum+i,sum+n,sum[i]+s)-sum;
minl = min(minl,end-i);
}
printf("%d\n",minl);
}
return 0;
}
解法二:对解法一改进的尺取法,对于区间[s,t),sum = As+As+1+...+At-2+At-1。我们注意到,
这次计算完后,区间往前推进,s=s+1,而新的t满足>=原有的t,sum直接在原有sum-As的基础上+value[t]更新即可。
复杂度O(n)
/*
@Filename: code.cpp
@Author: wyl6
@Mail: ustbcs_wyl@163.com
@Thought:
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <list>
#include <sstream>
#include <set>
#include <functional>
using namespace std;
#define INF 0x3f3f3f3f
#define MAX 100
typedef long long ll;
int m,n,S;
int v[100005];
int main(int argc, char const *argv[])
{
scanf("%d",&m);
while(m--) {
scanf("%d%d",&n,&S);
for (int i = 0; i < n; ++i) scanf("%d",&v[i]);
//尺取法
int s = 0,t = 0,sum = 0;
int res = n+1;
for (;;){
while(t < n && sum < S) sum += v[t++];
if(sum < S) break;
res = min(res,t-s);
sum -= v[s++];
}
if(res > n) res = 0;
printf("%d\n", res);
}
}