https://loj.ac/problem/10042#
题目描述
给出一段数字序列,求一段最长的连续的序列使其中的元素不重复。
思路
这道题显然想要我们给出(O(n))的算法,所以我们考虑用双指针,每当有指针右移时,判断加入的数是否出现过,出现过就接改变左指针。二是否出现过我们可以用(Hash)表维护,不过为了快速得到左指针的位置,我们插入每一个数时需要记录两个值,一个是模后的值,一个是位置。所以右指针右移时我们只要找到与它值相同的位置再右移一个就是最长的以它为右端点的序列。
代码
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const ull mod=1e6+9;
const ull MAXN=1e6+5;
ull nxt[MAXN],key[MAXN],poi[mod+5],num[MAXN],tot;
void insert(ull x,int p)
{
ull h=x%mod;
nxt[++tot]=poi[h];
poi[h]=tot;
key[tot]=x;
num[h]=p;
}
bool check(ull x)
{
int h=x%mod;
for(int i=poi[h];i;i=nxt[i])
if(key[i]==x)return 1;
return 0;
}
int main()
{
int n;
scanf("%d",&n);
ull ans=0,l=1;
for(int r=1;r<=n;r++)
{
ull a;
scanf("%llu",&a);
if(check(a)&&l<=num[a%mod])
l=num[a%mod]+1;
insert(a,r);
ans=max(ans,r-l+1);
}
printf("%llu",ans);
return 0;
}