尺取的用队列比较好理解吧!

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

对于这道题来说,用队列理解尺取感觉最合适不过了。

分析一下这个数据

代码思路按照如下分析写得。

5 1 3 5 10 7 4 9 2 8

 

5 1 3 5 10 7 4 9 2 8

 

5 1 3 5 10 7 4 9 2 8

 

5 1 3 5 10 7 4 9 2 8 ===》ans=2最终答案,最少序列

 

5 1 3 5 10 7 4 9 2 8

 

5 1 3 5 10 7 4 9 2 8

 

5 1 3 5 10 7 4 9 2 8

 

5 1 3 5 10 7 4 9 2 8

其实就是满足不满足条件出队。。。

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;

public class MainF {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int num = in.nextInt();
		int n,m;
		
		while(num--!=0) {
			n = in.nextInt();
			m = in.nextInt();
			Queue<Integer> queue = new LinkedList<Integer>();
			List<Integer> list = new ArrayList<Integer>();
			for(int i=0;i<n;i++) {
				list.add(in.nextInt());
			}

			Integer sum = 0;
			int ans = 999999999;
			for(int i=0;i<n ;i++) {
				        //如果值小就一直加
					while(i<n && sum + list.get(i)< m ) {
						queue.offer(list.get(i));
						sum+=list.get(i);
						i++;
					}
					if(i>=n)break;
					queue.offer(list.get(i));
					sum += list.get(i);
                                        //超过了给定值,就开始记录
					while(i<n && sum >= m ) {
						//先记录长度
						if(ans > queue.size()) {
							ans = queue.size();
						}
						if(!queue.isEmpty()) {
                                                        //出队,少一个元素看看总的值sum是否还大于给定值m
							Integer fileNum = queue.poll();
							sum-=fileNum;
						}else {
							break;
						}
						
					}

				
			}
			if (ans>n) ans = 0;
			System.out.println(ans);
		}
		
	}
	
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值