洛谷 P5679 [GZOI2017]等差子序列 题解
容易发现依次枚举中间数,维护桶,然后枚举差值判断。这样就是 \(O(Tn^2)\) 的。
string ask()
{
memset(c,0,sizeof(c));
for (int i=1;i<=n;i++) a[i]=read(),c[a[i]]++;
memset(b,0,sizeof(b));
c[a[1]]--;
for (int i=1;i<=n;i++)
{
for (int j=-MAXN;j<=MAXN;j++)
{
int x=a[i]-j,y=a[i]+j;
if (x<1||y<1||x>MAXN||y>MAXN) continue;
if (b[x]==0||c[y]==0) continue;
return "YES";
}
if (i!=n) b[a[i]]++,c[a[i+1]]--;
}
return "NO";
}
怎么优化?在枚举差值那一步,可以考虑 bitset。
由于要找到 \(a_x+a_y=2\times a_i(x<i<y)\),所以我们用两个 bitset 维护前面的桶和后面的桶。可以把和转化成差,用 bitset 的 & 判断。
于是时间复杂度是 \(O(\frac{TN^2}{w})\)。注意一些细节。
// By: Little09
// Problem: P5679 [GZOI2017]等差子序列
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P5679
// Memory Limit: 128 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
// By: Little09
// Problem: P5679 [GZOI2017]等差子序列
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P5679
// Memory Limit: 128 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
int T,n;
const int N=40005,MAXN=40000;
int a[N],b[N],c[N];
bitset<N>x,y,z;
inline int read()
{
char C=getchar();
int F=1,ANS=0;
while (C<'0'||C>'9')
{
C=getchar();
}
while (C>='0'&&C<='9')
{
ANS=ANS*10+C-'0';
C=getchar();
}
return F*ANS;
}
string ask()
{
x.reset(),y.reset();
memset(c,0,sizeof(c));
for (int i=1;i<=n;i++) a[i]=read(),c[a[i]]++;
memset(b,0,sizeof(b));
c[a[1]]--;
for (int i=1;i<=MAXN;i++) if (c[i]>0) y[i]=1;
for (int i=1;i<=n;i++)
{
z=((x>>(MAXN-2*a[i]))&y);
if (z.count()) return "YES";
if (i!=n)
{
if (b[a[i]]==0) x[MAXN-a[i]]=1;
b[a[i]]++,c[a[i+1]]--;
if (c[a[i+1]]==0) y[a[i+1]]=0;
}
}
return "NO";
}
int main()
{
cin >> T;
while (T--)
{
n=read();
cout << ask() << endl;
}
return 0;
}