用STL做会很方便
SET:
1 /*by SilverN*/ 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cstdio> 6 #include<cmath> 7 #include<set> 8 using namespace std; 9 const int mxn=1000020; 10 int a[mxn]; 11 int n,T; 12 int main(){ 13 scanf("%d",&T); 14 int i,j; 15 while(T--){ 16 scanf("%d",&n); 17 for(i=1;i<=n;i++)scanf("%d",&a[i]); 18 set<int>s; 19 int L=1,R=1; 20 int ans=0; 21 while(R<=n){ 22 while(R<=n && !s.count(a[R])) s.insert(a[R++]); 23 ans=max(ans,R-L); 24 s.erase(a[L++]); 25 } 26 printf("%d ",ans); 27 } 28 return 0; 29 }
MAP:
1 /*by SilverN*/ 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cstdio> 6 #include<cmath> 7 #include<map> 8 using namespace std; 9 const int mxn=1000020; 10 int a[mxn]; 11 int last[mxn]; 12 map<int,int>cur; 13 int T,n; 14 int main(){ 15 scanf("%d",&T); 16 while(T--){ 17 scanf("%d",&n); 18 int i,j; 19 cur.clear(); 20 for(i=1;i<=n;i++){ 21 scanf("%d",&a[i]); 22 //预处理 23 if(!cur.count(a[i]))last[i]=-1; 24 else last[i]=cur[a[i]]; 25 cur[a[i]]=i; 26 } 27 int L=1,R=1; 28 int ans=0; 29 while(R<=n){ 30 while(R<=n && last[R]<L)R++; 31 ans=max(ans,R-L); 32 L++; 33 } 34 printf("%d ",ans); 35 } 36 return 0; 37 }