尺取法

poj 3061 的题目用到非常简单的尺取法

在这里插入图片描述

1)首先设置四个变量b = e = sum = 0,res = n + 1,其中b为开始的下标,e为结束的下标,sum为从b取到e累加的和,res记录最短的长度
2)首先移动e的下标(e自加),直到从b累加到e的和sum >= s(s为题目中的设定值)
3)此时sum >= s可以记录长度res = Math.(res, e - b),在此之前先要判断是不是取完了,如果跳出循环还是sum < s 说明没有可以取的区间了,结束
4)缩短左边长度(b自加),试探性的减少左的值,即sum减去缩短的值
在d

Java代码
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		
		int c = sc.nextInt();
		
		for(int i = 0; i < c; i++) {
			int n = sc.nextInt();
			int s = sc.nextInt();
			
			int [] a = new int [n];
			
			for(int j = 0; j < n; j++) {
				a[j] = sc.nextInt();
			}
			
			int b = 0;
			int e = 0;
			int sum = 0;
			int res = n + 1;
			
			while(true) {
				
				while(e < n && sum < s) {
					sum += a[e++];
				}
				
				if(sum < s) break;
				
				res = Math.min(res, e - b);
				
				sum -= a[b++];
				
			}
			if(res > n) System.out.println(0);
			else System.out.println(res);
		}
		
	}

}
poj 3320

在这里插入图片描述
方法同上,只不过在开始之前先用set判断所有知识的个数,在选取区间时用map记录当前的知识各有多少个。

Java代码
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		
		int [] a = new int [n];
		Set<Integer> s = new HashSet<Integer>();
		Map<Integer, Integer> m = new HashMap<Integer, Integer>();
		
		for(int i = 0; i < n; i++) {
			a[i] = sc.nextInt();
			
			m.put(a[i], 0);
			s.add(a[i]);
		}
		
		int l = s.size();
		
		
		int b = 0;
		int e = 0;
		int sum = 0;
		
		int res = n;
		
		while(true) {
			
			while(sum < l && e < n) {
				if(m.get(a[e]) == 0) {
					sum++;
				}
				m.put(a[e], m.get(a[e]) + 1);
				e++;
			}
			
			if(sum < l) break;
			
			res = Math.min(res, e - b);
			
			m.put(a[b], m.get(a[b]) - 1);
			if(m.get(a[b]) == 0) {
				sum--;
			}
			b++;
		}
		
		System.out.println(res);
		
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值