Emily the entrepreneur has a cool business idea: packaging and selling snowflakes. She has devised a
machine that captures snowflakes as they fall, and serializes them into a stream of snowflakes that flow,
one by one, into a package. Once the package is full, it is closed and shipped to be sold.
The marketing motto for the company is “bags of uniqueness.” To live up to the motto, every
snowflake in a package must be different from the others. Unfortunately, this is easier said than done,
because in reality, many of the snowflakes flowing through the machine are identical. Emily would like
to know the size of the largest possible package of unique snowflakes that can be created. The machine
can start filling the package at any time, but once it starts, all snowflakes flowing from the machine
must go into the package until the package is completed and sealed. The package can be completed
and sealed before all of the snowflakes have flowed out of the machine.
Input
The first line of input contains one integer specifying the number of test cases to follow. Each test
case begins with a line containing an integer n, the number of snowflakes processed by the machine.
The following n lines each contain an integer (in the range 0 to 109
, inclusive) uniquely identifying a
snowflake. Two snowflakes are identified by the same integer if and only if they are identical.
The input will contain no more than one million total snowflakes.
Output
For each test case output a line containing single integer, the maximum number of unique snowflakes
that can be in a package.
Sample Input
1
5
1
2
3
2
1
Sample Output
3
题意:给出一串数字序列,你从中找出一串最长的连续、数字并不相同的序列的最大数目
该开始并未读懂题意,但是想到使用set来做,之后根据题意我们就可以有以下的思路:
我们可以设置一个移动窗口(L,R),通过这个窗口来处理这个序列,先从R = 0开始,R++,如果之前没有出现,那么就存入到set中,并且每次记录出set的最大长度,当遇到之前已经出现的数字就停下,然后从L开始删除这些元素,一直到L等于R为止,然后又从R开始增加,和上面的规律一样。直到R = n的时候,那么这个记录的最大长度就是,所求序列的最大数目
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
set<int> s;
vector<int> v;
int main()
{
int i,t,n,temp;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
s.clear();
v.clear();
for(i = 0;i < n;i++)
{
scanf("%d",&temp);
v.push_back(temp);
}
int l = 0,r = 0,imax = 0;
for(r = 0;r < n;r++)
{
while(s.count(v[r])) //这里通过函数s.count()来判断是否出现过这个数字
{
s.erase(v[l]); //函数s.erase()删除set里面的这个数字
l++;
}
s.insert(v[r]);
imax = max(imax, (int)s.size()); //通过比较不断地更新最大的数目
}
printf("%d\n",imax);
}
return 0;
}