UVA-11572-Unique Snowflakes

原题
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
题意:
题目大致意思是有t个测试用例,每一个是由n个数字组成的序列,要我们从中找到最长的子序列,要求子序列中不能够有相同的元素。
题解:
这道题目,没有什么难度就是暴力枚举,移动窗口。定义一个左右边界left和right,简写l和r。从首位到末位枚举每一个位置作为右边界,并且每一次都判断在左右边界里面是否有相同的元素,若是有则将左边界更新为此相同元素的位置,最终答案和r-l比较,始终取最大值。
注:这道题目我开始自己用函数写了判断区间内是否有相同元素,结果TLE。最后选择了map利用键值来判断,这样提高了查找效率,自然不会TLE了。
附上AC代码:

#include <iostream>
#include <map>
using namespace std;
int num[1000005];
int t,n,l,r,ans;
map<int,int> vis;//用来标记每一个数值在当前序列中第一次出现的位置
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>n;
        for(int i=1;i<=n;i++)
            cin>>num[i];
        vis.clear();//初始化map
        l=0,r=1,ans=1;//初始化左右边界
        while(r<=n)
        {
            if (vis[num[r]] > l)//如果在l-r区间内出现了相同的数值则更新左边界
                l = vis[num[r]];
            vis[num[r]] = r;
            ans=(r-l)>ans?(r-l):ans;//不断更新最大值
            r++;//右边界++
        }
        cout<<ans<<endl;
    }
    return 0;
}

欢迎评论!

猜你喜欢

转载自blog.csdn.net/wjl_zyl_1314/article/details/82987832