1. 程式人生 > >UVA1121 Subsequence(二分or 尺取)

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;
	}	
}

尺取我明天再寫