Unique Snowflakes UVA - 11572

这里写图片描述
大意:求最大不重复连续数列的长度
题解:
1.段查找问题,紫书上有,滑动窗口方式。
2.用set集合类存储,用set存数是有序的
3.先给定一个区间长度,当右端数字在set中一直没出现就一直往右扩展while(!st.count(a[r])&&r<=n) st.insert(a[r++]);
4.当重复时,去掉左端的数字st.erase(a[l++]);
5.每次更新ans值。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
using namespace std;
int n,T;
long long a[1000005];
set<long long> st;
int main()
{


    cin>>T;
    while(T--)
    {
        scanf("%d",&n);
        for(int i = 1 ; i <= n ; i++)
        scanf("%lld",&a[i]);

        st.clear();

        int l = 1,r = 1,ans = 0;
        while(r<=n)
        {
            while(!st.count(a[r])&&r<=n)//一定让r<=n,不然会出现-234234234之类的a[r] 
            {
                st.insert(a[r]);
                r++;
            }
            ans = max(ans,r-l);
            if(r>n) break;//如果超过n,也没必要让下一句话继续下去了 ; 
            st.erase(a[l++]);
        }

        cout<<ans<<endl;
    }
    return 0;
}
阅读更多

Unique Snowflakes

09-05

Problem DescriptionnEmily 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.nnThe 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.n nnInputnThe first line of each test chunk contains an integer specifying the number of test cases in this chunk 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 10^9, 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. nPlease process to the end of the data file.n nnOutputnFor each test case output a line containing single integer, the maximum number of unique snowflakes that can be in a package.n nnSample Inputn1n5n1n2n3n2n1n1n5n1n2n3n2n1n nnSample Outputn3n3n

没有更多推荐了,返回首页