解题报告 之 UVA11572 Unique Snowflakes

来源:互联网 发布:php print r 编辑:程序博客网 时间:2024/06/13 00:10

解题报告 之 UVA11572 Unique Snowflakes

Description

Download as PDF

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
题目大意:从一个有n个数的序列中,找到一个最大的子序列,使得这个最大子序列中没有重复元素,输出最大子序列的长度。
分析:我一开始的自然想法是肯定得从头开始扫描,一直扫啊扫到出现了之前有重复元素为止。然后再将最大长度更新一下,把左边界前进到重复元素后一个元素。一直重复这个更新的过程直到扫完。但是发现要记录每个元素的位置是一个很麻烦的事情。后来参考大紫书,发现其实不需要直接跳到重复元素之后,可以假设当前的左边界就是重复元素,试探性的跳,如果左边界不是重复元素的话也无妨,反正也得跳。。。就这么一直试探直到找到重复元素为止,这样复杂度也是满足的,而且很方便。
所以总的来说最大的收获就是再复杂度满足的情况下可以退一步用更原始的方法来实现。
上代码:
#include <iostream>#include <algorithm>#include <set>using namespace std;int num[1000010];int main(){int kase;cin >> kase;while (kase--){int n;cin >> n;for (int i = 0; i < n; i++)cin >> num[i];set<int> s;int l = 0, r = 0, max = 0, ml=0, mr=0;while(r<n){if (s.find(num[r]) == s.end()){s.insert(num[r]);r++;if (r - l>max){max = r - l;ml = l;mr = r;}}else{s.erase(num[l]);l++;}}cout << mr - ml  << endl;}return 0;}

还有好多题,,我做不完啦!
0 0