UVA 11572 - Unique Snowflakes

输入一个长度为n(n <= 106)的序列A,找到一个尽量长的连续子序列AL~AR,使得该序列中没有相同得元素。
一开始用得map做的,用变量s存储子序列开始下标。
然后用map存储子序列中每个数字出现的下标。
然后从左到右枚举子序列结束下标i,当map[a[i]]的值不为零时,需要把map[s]~map[a[i]]的值改为0,才能继续向后扩展。
但是用map做的代码超时了,然后看了紫书中的分析,用的是set做的。
改了一下就过了。

#include <stdio.h>
#include <algorithm>
#include <set>
using namespace std;
int a[1000005];
int main()
{
    int s, T, n;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d", &n);
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &a[i]);
        }
        set<int> ss;
        int ans = 1;
        ss.insert(a[1]);
        s = 1;
        for(int i = 2; i <= n; i++)
        {
            while(ss.find(a[i]) != ss.end())
            {
                ss.erase(a[s++]);
            }
            ss.insert(a[i]);
            ans = max(ans, i - s + 1);
        }
        printf("%d\n", ans);
    }
    return 0;
}

或者用map和last数组预处理后,也可以通过此题。

#include <stdio.h>
#include <algorithm>
#include <map>
using namespace std;
int a[1000005], last[1000005];
int main()
{
    int s, T, n;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d", &n);
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &a[i]);
        }
        map<int, int> mp;
        for(int i = 1; i <= n; i++)
        {
            if(mp[a[i]] == 0)
                last[i] = -1;
            else
                last[i] = mp[a[i]];
            mp[a[i]] = i;
        }
        int ans = 1;
        int s = 1;
        for(int i = 2; i <= n; i++)
        {
            while(last[i] != -1 && last[i] >= s)
            {
                ++s;
            }
            ans = max(ans, i - s + 1);
        }
        printf("%d\n", ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值