Unique Snowflakes UVA - 11572
题目如下
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
题意
我们有一个长度不超过10的9次方的序列,题要求我们求出这个序列中连续不重复元素的最长子序列的长度。比如说列题就是 1 2 3;
- 这里面如果你直接定义一个10的9次方,你的vs可能会报错,交的时候可能爆内存所以我这里建议使用queue或者deque,因为我们要后面添加数字,前面把不符合的排出去,这样可以不断释放内存。
- 我们这里使用sort函数,这个函数他会自己将重复的数字删去;而queue不会所以两个size不相等的时候,说明有数字重复了,记下那个重复的数字(假设为k)和sort的size,然后用queue函数,这里有一个queue便利的地方那就是queue是从前往后删的,而且可以查看第一个数字,然后用sort的find这个第一个数并且删去,一直删直到第一个数字等于k然后把queue里面的k也删了,就不用那么复杂的去记left,right;时不时的跟新max就行了。逻辑挺简单。
下面给出AC代码
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<set>
#include<cstdio>
#include<queue>
using namespace std;
int main()
{
int t, i, m, sum, max, n;
sum = 0;
max = 0;
set<int>di;
queue<int>bi;
cin >> t;
while (t--)
{
cin >> m;
for (i = 0; i < m; i++)
{
cin >> n;
di.insert(n);
bi.push(n);
if (bi.size() != di.size())//在输入数字的时候就开始检查
{
sum = di.size();
if (sum > max)
max = sum;//记下目前最大值
while (1)
{
if (bi.front() != n)//查看queue第一个数字
{
di.erase(bi.front());//删去sort里面的
bi.pop();//删去queue里面的
}
else//sort里面的不要删,因为只有一个,函数已经帮你删
{
bi.pop();//而queue里面有两个,手动删
break;
}
}
}
}
sum = di.size();
if (sum > max)
max = sum;//最后的时候不会执行while,所以手动执行
printf("%d\n", max);
di.clear();//这边就是清空队列了
while(1)
{
if (bi.size() != 0)
{
bi.pop();
}
else
break;
}
sum = 0;
max = 0;
}
return 0;
}