题目描述
给定一个长度为 nn 的序列 a1,a2,⋯ ,ana1,a2,⋯,an 和一个常数 SS。
对于一个连续区间如果它的区间和大于或等于 SS,则称它为美丽的区间。
对于一个美丽的区间,如果其区间长度越短,它就越美丽。
请你从序列中找出最美丽的区间。
输入描述
第一行包含两个整数 n,Sn,S,其含义如题所述。
接下来一行包含 nn 个整数,分别表示 a1,a2,⋯ ,ana1,a2,⋯,an。
10≤N≤10510≤N≤105,1×ai≤1041×ai≤104,1≤S≤1081≤S≤108。
输出描述
输出共一行,包含一个整数,表示最美丽的区间的长度。
若不存在任何美丽的区间,则输出 00。
输入输出样例
示例 1
输入
5 6
1 2 3 4 5
输出
2
运行限制
- 最大运行时间:1s
- 最大运行内存: 128M
AC代码:
import javax.persistence.criteria.CriteriaBuilder;
import javax.print.DocFlavor;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main
{
static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static int N = (int)1e3 + 10;
static int a[] = new int[N];
static int s[] = new int[N];
public static void main(String[] args ) throws IOException
{
int n = rd.nextInt();
int target = rd.nextInt();
for(int i = 1 ; i <= n ; i ++) a[i] = rd.nextInt();
for(int i = 1 ; i <= n ; i ++) s[i] = s[i - 1] + a[i];
int res = Integer.MAX_VALUE;
// 枚举区间的左端点
for(int i = 1 ; i <= n ; i ++)
{
// 二分找区间的右端点,答案尽可能向左
int l = i , r = n;
while(l <= r)
{
int mid = l + r >> 1;
if(s[mid] - s[i - 1] == target) r = mid - 1;
else if(s[mid] - s[i - 1] > target) r = mid - 1;
else if(s[mid] - s[i - 1] < target) l = mid + 1;
}
if(s[r + 1] - s[i - 1] >= target) res = Math.min(res,r + 1 - i + 1); // 该区间满足题目条件,更新区间的长度
}
if(res == Integer.MAX_VALUE) pw.println(0);
else pw.println(res);
pw.flush();
}
}
class rd
{
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static String nextLine() throws IOException { return reader.readLine(); }
static String next() throws IOException
{
while(!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
static int nextInt() throws IOException { return Integer.parseInt(next()); }
static double nextDouble() throws IOException { return Double.parseDouble(next()); }
static long nextLong() throws IOException { return Long.parseLong(next()); }
static BigInteger nextBigInteger() throws IOException
{
BigInteger d = new BigInteger(rd.nextLine());
return d;
}
}
class PII implements Comparable<PII>
{
int x,y;
public PII(int x ,int y)
{
this.x = x;
this.y = y;
}
public int compareTo(PII a)
{
if(this.x-a.x != 0)
return this.x-a.x; //按x升序排序
else return this.y-a.y; //如果x相同,按y升序排序
}
}
class Edge
{
int a,b,c;
public Edge(int a ,int b, int c)
{
this.a = a;
this.b = b;
this.c = c;
}
}

文章提供了一个编程问题的描述,要求在给定序列中找到和大于或等于指定值的最短连续区间。这个问题可以通过动态求区间和并使用二分查找来解决。给出的Java代码实现了这个算法,找出满足条件的最短区间长度。当没有美丽区间时,输出0。

被折叠的 条评论
为什么被折叠?



