还是一个字——栈
然后加一大堆特判
至少我是这么做的
我的代码
#include <cstdio>
#include <iostream>
#define N 100001
#define max(x, y) ((x) > (y) ? (x) : (y))
int s[N], a[N], b[N];
int n, top, ans;
inline int read()
{
int x = 0, f = 1;
char ch = getchar();
for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
return x * f;
}
int main()
{
int i, x;
n = read();
for(i = 1; i <= n; i++)
{
a[i] = read();
b[a[i]]++;
}
for(i = 1; i <= n; i++)
{
if(!top && !a[i]) continue;
else if(!a[i])
{
s[++top] = a[i];
continue;
}
if(s[top] == a[i] && b[a[i]] > 1)
{
ans = max(ans, top);
b[a[i]]--;
}
else if(s[top] == a[i] && b[a[i]] == 1)
{
ans = max(ans, top);
b[a[i]]--;
top--;
}
else if(b[a[i]] == 1) ans = max(ans, top + 1);
else
{
s[++top] = a[i];
b[a[i]]--;
}
}
if(top) puts("-1");
else printf("%d\n", ans);
return 0;
}
看了题解
发现预处理出来每种颜色最左边和最右边的位置会更好处理
如果两种颜色有交集,直接输出-1
题解代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int n;
int a[100008],l[100008],r[100008];
int s[100008],top;
int tmp,ans;
int main()
{
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
if(!l[a[i]]) l[a[i]]=i;
r[a[i]]=i;
}
for(int i=1;i<=n;i++){
if(a[i]==0){
if(top){
cout<<-1;
return 0;
}
else continue;
}
if(l[a[i]]==i){
if(top&&r[a[i]]>r[s[top]]){
cout<<-1;
return 0;
}
s[++top]=a[i];
tmp++;
ans=max(ans,tmp);
}
if(r[a[i]]==i){
top--;
tmp--;
}
}
cout<<ans;
return 0;
}
5
1 2 1 2 1
这组数据,我输出-1,题解输出2
好像题解错了,但因为数据水,所以,你懂的