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减去缩短的值

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);
}
}
本文介绍了使用尺取法解决特定序列问题的两种方法,并提供了详细的Java代码实现。第一种方法用于寻找序列中和大于等于设定值的最短连续子序列,第二种方法则用于找出包含所有指定元素的最小子序列。通过具体的POJ题目的解析,读者可以深入理解尺取法的应用。
1984

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



