package Week1; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A_Subsequence { static int T,N,S; static int arr[]; static int s,e; static int ans; static int count; // 2 // 10 15 // 5 1 3 5 10 7 4 9 2 8 // 5 11 // 1 2 3 4 5 //快慢指针,s=1,e=i等于for循环的i然后每个数相加和,判断累加和不满足时, ans>=S && s<=e,让ans-arr[s],然后慢指针右移动1,s=s+1 //继续判断累加和是否大于S,大于不满足继续右移动s=s+1小于S即求最大长度count=Math.min(count, e-s+1); /* * 给出了N个正整数(10<N<100000)的序列,每个正整数小于或等于10000,以及一个正整数S(S<100000)。编写一个程序, * 求序列中连续元素的子序列的最小长度,其和大于或等于S。 输入 * 第一行是测试用例的数量。对于每个测试用例,程序必须从第一行读取数字N和S,以间隔隔开。序列号在测试用例的第二行给出,用间隔隔开。输入将在文件结束时完成。 * 输出 对于每种情况,程序都必须在输出文件的单独一行上打印结果。如果没有答案,则打印0。 */ public static void main(String[] args) throws Exception { System.setIn(new FileInputStream("Solution.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = null; st = new StringTokenizer(br.readLine()); T = Integer.parseInt(st.nextToken()); for (int t = 1; t <= T; t++) { st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); S = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); arr = new int[N+1]; for (int i = 1; i <= N; i++) { arr[i]=Integer.parseInt(st.nextToken()); } s=1; count=Integer.MAX_VALUE/2; ans = arr[1]; for ( e = 2; e <= N; e++) { ans += arr[e]; while(ans>=S && s<=e) { count=Math.min(count, e-s+1); ans -= arr[s]; s = s+1; } } if(count == Integer.MAX_VALUE/2) { System.out.println(0); }else { System.out.println(count); } } } }