| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 12969 | Accepted: 4442 |
Description
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
题目链接:http://poj.org/problem?id=3320
题意:一个长度为P的序列,问覆盖序列中所有不同数字的最短长度。
解题思路:采用集合set记录不同数字的个数n,用map来记录每个数字在区间中出现的次数。采用尺取法当下标小于P和不同数字之和小于n时循环。当每次循环结束时如果不同数字之和小于n那么再往后查找也就没有意义了,此时跳出最外层循环,否则更新ans。
AC代码:
#include<cstdio>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
const int MAXP = 1000000+7;
int P;
int a[MAXP];
int n;
void solve()
{
int s=0,t=0,num=0;
map<int,int> count;//记录每个知识点出现的次数
int ans=P;
for(;;)
{
while(t<P && num<n)//还没阅读到最后一页和知识点个数还没有完全覆盖时循环
{
int idea=a[t];
if(count[idea]==0)//出现新的知识点
{
num++;
}
count[idea]++;
t++;//向后翻一页
}
if(num<n) break;//如果上一次查找知识点的个数已经不能覆盖时此后再翻新也是无意义的
ans=min(ans,t-s);//更新最小翻阅次数
if(--count[a[s++]]==0)//如果当前查找的第一页的知识点只在第一页出现那么下一次翻新时要作为一个新的知识点
{
num--;
}
}
printf("%d\n",ans);
}
int main(void)
{
set<int> all;//利用集合中各元素各不相同
scanf("%d",&P);
for(int i=0;i<P;i++)
{
scanf("%d",&a[i]);
all.insert(a[i]);
}
n=all.size();//记录知识点的个数
solve();
return 0;
}
Jessica面临考试,需找到课本中覆盖所有知识点的最短连续部分。本文介绍如何通过编程解决此问题,采用尺取法和数据结构如集合与映射来高效求解。
305

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



