POJ3061 尺取法

n个数字,求最短的连续的数字长度,满足和>=s

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) {
		new POJ3061().solve();
	}
}

class POJ3061 {

	InputReader in = new InputReader(System.in);
	PrintWriter out = new PrintWriter(System.out);
	final int N = 100008;
	int[] a = new int[N];

	void solve() {
		int t = in.nextInt();
		while (t-- > 0) {
			int n = in.nextInt();
			int s = in.nextInt();
			for (int i = 0; i < n; i++)
				a[i] = in.nextInt();

			int start = 0, end = 0, sum = 0, res = n + 1;
			for (;;) {
				while (end < n && sum < s) {
					sum += a[end++];
				}
				if (sum < s)
					break;
				res = Math.min(res, end - start);
				sum -= a[start++];
			}
			out.println(res == n + 1 ? 0 : res);
		}
		out.flush();
	}
}

class InputReader {
	public BufferedReader reader;
	public StringTokenizer tokenizer;

	public InputReader(InputStream stream) {
		reader = new BufferedReader(new InputStreamReader(stream), 32768);
		tokenizer = new StringTokenizer("");
	}

	private void eat(String s) {
		tokenizer = new StringTokenizer(s);
	}

	public String nextLine() {
		try {
			return reader.readLine();
		} catch (Exception e) {
			return null;
		}
	}

	public boolean hasNext() {
		while (!tokenizer.hasMoreTokens()) {
			String s = nextLine();
			if (s == null)
				return false;
			eat(s);
		}
		return true;
	}

	public String next() {
		hasNext();
		return tokenizer.nextToken();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public long nextLong() {
		return Long.parseLong(next());
	}

	public double nextDouble() {
		return Double.parseDouble(next());
	}

	public BigInteger nextBigInteger() {
		return new BigInteger(next());
	}

}




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013491262/article/details/52347141
个人分类: Java足迹
上一篇POJ1064二分
下一篇spring mybatis整合
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭