洛谷 P5679 [GZOI2017]等差子序列 题解

容易发现依次枚举中间数,维护桶,然后枚举差值判断。这样就是 O(Tn2) 的。

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。

由于要找到 ax+ay=2×ai(x<i<y),所以我们用两个 bitset 维护前面的桶和后面的桶。可以把和转化成差,用 bitset 的 & 判断。

于是时间复杂度是 O(TN2w)。注意一些细节。

// 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;
}

posted @   Little09  阅读(207)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示