POJ - 3061 Subsequence(连续子序列和>=s的最短子序列长度)

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

Sample Output

题目链接:http://poj.org/problem?id=3061

*******************************************

题意:T组实例,每组实例给出n和s,接着n个数。求连续子序列和大于等于s的最短子序列长度。

分析:有点点模拟的意思,形象点说,就像你堆积木,超过一定值S后我们就把最下面的几块积木去掉。具体方法是从前面开始不断累加,当和值超过S时减少前面的数值,然后记录下刚好>=S的ans值,如此重复直到序列尾,输出最小的ans。

AC代码1:

 #include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
#include<time.h>
#include<stack>
using namespace std;
#define N 1200000
#define INF 0x3f3f3f3f int dp[N];
int a[N]; int main()
{
int n,m,T,i,j; scanf("%d", &T); while(T--)
{
scanf("%d %d", &n, &m);
memset(dp,,sizeof(dp)); for(i=;i<=n;i++)
{
scanf("%d", &a[i]);
dp[i]=dp[i-]+a[i];
} int minn=INF,i=;;
for(j=;j<=n;j++)
{
if(dp[j]-dp[i-]<m)
continue ;
while(dp[j]-dp[i]>=m)
i++;
minn=min(minn,j-i+);
} if(minn==INF)
printf("0\n");
else
printf("%d\n", minn);
}
return ;
}

AC代码2:(运用二分函数)

这里用到二分函数是找到刚好>=s的那个ans

 #include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
#include<time.h>
#include<stack>
using namespace std;
#define N 1200000
#define INF 0x3f3f3f3f int dp[N];
int a[N]; int main()
{
int n,m,T,i; scanf("%d", &T); while(T--)
{
scanf("%d %d", &n, &m);
memset(dp,,sizeof(dp)); for(i=;i<=n;i++)
{
scanf("%d", &a[i]);
dp[i]=dp[i-]+a[i];
} int minn=INF;
for(i=;i<=n;i++)
if(dp[n]-dp[i-]>=m)
{
int ans=lower_bound(dp,dp+n,dp[i-]+m)-dp;///二分函数
minn=min(ans-i+,minn);
} if(minn==INF)
printf("0\n");
else
printf("%d\n", minn);
}
return ;
}
上一篇:【DP_背包专题】 背包九讲


下一篇:mysql命令使用