UVA1121 Subsequence(二分or 尺取)

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

呃呃呃 二分 就是前缀和,,然后枚举每一个n 可以到哪个地方会大于等于 时间复杂的为nlog(n)

代码:

import java.util.Arrays;
import java.util.Scanner;
public class Main {
	static Scanner sc = new Scanner(System.in); 
	static final int N = 100005;
	static int digit[] = new int [N];
	public static void main(String[]args)
	{
		int t = sc.nextInt();
		while(t-- > 0)
		{
			int num = sc.nextInt();
			int total = sc.nextInt();
			for(int i = 1; i <= num; i++)
			{
				digit[i] = 0;
				int x  = sc.nextInt();
				digit[i] = x + digit[i - 1];
			}
			if(digit[num] < total)
				System.out.println(0);
			else 
				System.out.println(Binary_Search(total,num));
		}
	}
	private static int Binary_Search(int total,int num) {
		int maxn = Integer.MAX_VALUE;
		for(int i = 1; i <= num; i++)
		{
			int left = i, right = num;
			while(left <= right) //现在要找的是第一个大于等于他的值
			{
				int mid = (left + right) >> 1;
				if(digit[mid] - digit[i - 1] >= total) {
					right = mid - 1;
				}else 
					left = mid + 1;
			}
			if(left <= num && digit[left] - digit[i - 1] >= total)
			{
				int gg = left - i + 1;
				maxn = Math.min(maxn, gg);
			}
		}	
		return maxn;
	}	
}

尺取我明天再写

猜你喜欢

转载自blog.csdn.net/galesaur_wcy/article/details/83794374