当前位置: 首页 > 工具软件 > Jessica > 使用案例 >

Jessica‘s Reading Problem(尺取法)

荣晨朗
2023-12-01

Jessica’s Reading Problem (尺取法)

Jessica’s a very lovely girl wooed by lots of boys. Recently she has a problem. The final exam is coming, yet she has spent little time on it. If she wants to pass it, she has to master all ideas included in a very thick text book. The author of that text book, like other authors, is extremely fussy about the ideas, thus some ideas are covered more than once. Jessica think if she managed to read each idea at least once, she can pass the exam. She decides to read only one contiguous part of the book which contains all ideas covered by the entire book. And of course, the sub-book should be as thin as possible.

A very hard-working boy had manually indexed for her each page of Jessica’s text-book with what idea each page is about and thus made a big progress for his courtship. Here you come in to save your skin: given the index, help Jessica decide which contiguous part she should read. For convenience, each idea has been coded with an ID, which is a non-negative integer.

Input
The first line of input is an integer P (1 ≤ P ≤ 1000000), which is the number of pages of Jessica’s text-book. The second line contains P non-negative integers describing what idea each page is about. The first integer is what the first page is about, the second integer is what the second page is about, and so on. You may assume all integers that appear can fit well in the signed 32-bit integer type.

Output
Output one line: the number of pages of the shortest contiguous part of the book which contains all ideals covered in the book.

Sample Input
5
1 8 8 8 1
Sample Output
2

题意: 给你一个n,下面有n个数。求一个最短的区间,使这n个数都在这个区间出现过至少一次。

思路: 数据太大,所以需要用尺取法降低时间复杂度,尺取法就是定义l,r左边界和右边界,r++直到区间满足题意,然后开始缩区间,即l++,遍历一遍后,得答案,因为这题数据太大,数组会爆掉,所以用到了set和map。

AC代码:

个人感觉这个代码更好理解一些

#include<stdio.h>
#include<string.h>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
int a[1100000];
int main()
{
	int t,n,s,i,j=0,k,sum,c;
	set<int>set;
	scanf("%d",&n);
	for(i=0; i<n; i++)
	{
		scanf("%d",&a[i]);
		set.insert(a[i]);//插入,set本身就有去重功能
	}
	j=set.size();//集合中元素的数目,即有几个不同的数
	map<int,int>map;//标记
	int l=0,r=0,ans=0x3f3f3f;
	sum=0;
	k=0;
	while(l<=r&&r<=n)
	{
		if(sum==j)//如果区间满足题意
		{
			ans=min(ans,r-l);//取区间最小值
			//	printf("%d  %d  %d----\n",ans,l,r);
			map[a[l]]--;//l要右移,减去一次
			if(map[a[l]]==0)//如果为0,说明l++后的区间中没有a[l],个数减少
			sum--;
			l++;
		//	printf("%d****\n",sum);
		}
		else
		{
			if(map[a[r]]==0)//如果之前没有出现过
			sum++;//记录目前有几个不同的数
			map[a[r]]++;//printf("%d++++\n",a[r]);	//记录这个数出现了几次
		//	printf("%d>>>>>\n",sum);
			r++;
		}
	}
	printf("%d\n",ans);
	return 0;
}
 类似资料: