【ST表 前缀和】P7809 [JRKSJ R2] 01 序列|普及+

本文涉及知识点

ST表
C++算法:前缀和、前缀乘积、前缀异或的原理、源码及测试用例 包括课程视频

P7809 [JRKSJ R2] 01 序列

题目背景

upd2021.8.16 \text{upd2021.8.16} upd2021.8.16:增加两组 hack 数据,并缩小时限至 1.2s。

题目描述

给你一个长度为 n n n 的 01 01 01 序列 a a a, m m m 次询问,支持 2 2 2 种询问:

  • 1 l r 表示询问 l l l 到 r r r 区间的最长不下降子序列的长度。
  • 2 l r 表示询问 l l l 到 r r r 区间的最长上升子序列的长度。

输入格式

输入 m + 2 m+2 m+2 行。

第 1 1 1 行两个正整数 n , m n,m n,m。

第 2 2 2 行 n n n 个数字 0 0 0 或 1 1 1 代表序列 a a a。

接下来 m m m 行每行三个正整数表示一次询问,格式如上。

输出格式

输出 m m m 行。

对于每一次询问求出答案并输出。

输入输出样例 #1

输入 #1

复制代码
8 4
0 1 1 0 1 0 0 1
1 1 8
2 1 8
1 3 6
2 5 6

输出 #1

复制代码
5
2
2
1

说明/提示

本题采用捆绑测试。

Subtask \text{Subtask} Subtask n ≤ n\le n≤ m ≤ m\le m≤ 特殊性质 分值
1 \text{1} 1 10 6 10^6 106 10 6 10^6 106 所有 a i a_i ai 均相等 5 5 5
2 \text{2} 2 10 3 10^3 103 10 3 10^3 103 10 10 10
3 \text{3} 3 10 4 10^4 104 10 4 10^4 104 15 15 15
4 \text{4} 4 10 5 10^5 105 10 5 10^5 105 30 30 30
5 \text{5} 5 10 6 10^6 106 5 × 10 6 5\times10^6 5×106 40 40 40
6 \text{6} 6 10 6 10^6 106 5 × 10 6 5\times10^6 5×106 hack 数据 0 0 0

对于 100 % 100\% 100% 的数据, 1 ≤ n ≤ 10 6 1\le n\le 10^6 1≤n≤106, 1 ≤ m ≤ 5 × 10 6 1\le m\le 5\times10^6 1≤m≤5×106, 0 ≤ a i ≤ 1 0\le a_i\le 1 0≤ai≤1。


本题输入输出量极大,这里给出出题人使用的快读快写。(当然,使用您自己编写的大概率也能通过)

cpp 复制代码
namespace IO{//by cyffff
	int len=0;
	char ibuf[(1<<20)+1],*iS,*iT,out[(1<<26)+1];
	#define gh() (iS==iT?iT=(iS=ibuf)+fread(ibuf,1,(1<<20)+1,stdin),(iS==iT?EOF:*iS++):*iS++)
	#define reg register
	inline int read(){
		reg char ch=gh();
		reg int x=0;
		reg char t=0;
		while(ch<'0'||ch>'9')   t|=ch=='-',ch=gh();
		while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=gh();
		return t?-x:x;
	}
	inline void putc(char ch){
		out[len++]=ch;
	}
	template<class T>
	inline void write(T x){
		if(x<0)putc('-'),x=-x;
		if(x>9)write(x/10);
		out[len++]=x%10+48;
	}
	inline void flush(){
		fwrite(out,1,len,stdout);
		len=0;
	}
}
using IO::read;
using IO::write;
using IO::flush;
using IO::putc;

使用这种快读快写读入一个数 x x x 时请使用语句 x=read();,输出时使用语句 write(x);。注意,换行时需使用语句 putc('\n');,程序执行结束时使用语句 flush();

在使用此快读时请加上 #include<bits/stdc++.h>

如果本地无法输入,可以尝试使用 这里的快读快写

若仍看不懂,请在赛时答疑帖回复/私信出题人。

由于出题人只会 C++,本处无法给出其他语言的快读快写,深感歉意。


样例解释:

对于第一个询问,满足的序列有: { 0 , 1 , 1 , 1 , 1 } , { 0 , 0 , 0 , 0 , 1 } \{0,1,1,1,1\},\{0,0,0,0,1\} {0,1,1,1,1},{0,0,0,0,1}。

对于第二个询问,满足的序列有: { 0 , 1 } \{0,1\} {0,1}。

对于第三个询问,满足的序列有: { 0 , 0 } , { 0 , 1 } , { 1 , 1 } \{0,0\},\{0,1\},\{1,1\} {0,0},{0,1},{1,1}。

对于第四个询问,满足的序列有: { 0 } , { 1 } \{0\},\{1\} {0},{1}。

本题时限、空限保证为出题人所用的两倍以上。

如果您仍认为卡常,则请私信出题人或者发帖并 @ 出题人。

ST表 前缀和

preSum记录a的前i个元素中1的数量。

st表st[i][j]记录a[i...i+2j-1]的非下降子序列长度。

已知[left,r)中最长非下降子序列是x1,[r,r2)中非下降子序列是x2。[left,r)中0的数量是c0,[r,r2)中1的数量是c1。

则:[left,r2)的最长递增子序列是以下值的最大值:

c0+x2:不存在1,或第一1在第二部分。

x1+c1:1第一个1在第一部分。

第一问:长度拆分成2的幂的如果段,分别查询。

第二问:用两个数组分别记录0和1的下标,二分区间0和1,如果0、1都存在,且0的最小下标 < 1的最大下标,则长度是2;否则是1。

代码

核心代码

cpp 复制代码
#include <iostream>
#include <sstream>
#include <vector>
#include<map>
#include<unordered_map>
#include<set>
#include<unordered_set>
#include<string>
#include<algorithm>
#include<functional>
#include<queue>
#include <stack>
#include<iomanip>
#include<numeric>
#include <math.h>
#include <climits>
#include<assert.h>
#include<cstring>
#include<list>

#include <bitset>
using namespace std;

template<class T1, class T2>
std::istream& operator >> (std::istream& in, pair<T1, T2>& pr) {
	in >> pr.first >> pr.second;
	return in;
}

template<class T1, class T2, class T3 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3>& t) {
	in >> get<0>(t) >> get<1>(t) >> get<2>(t);
	return in;
}

template<class T1, class T2, class T3, class T4 >
std::istream& operator >> (std::istream& in, tuple<T1, T2, T3, T4>& t) {
	in >> get<0>(t) >> get<1>(t) >> get<2>(t) >> get<3>(t);
	return in;
}

template<class T = int>
vector<T> Read() {
	int n;
	cin >> n;
	vector<T> ret(n);
	for (int i = 0; i < n; i++) {
		cin >> ret[i];
	}
	return ret;
}
template<class T = int>
vector<T> ReadNotNum() {
	vector<T> ret;
	T tmp;
	while (cin >> tmp) {
		ret.emplace_back(tmp);
		if ('\n' == cin.get()) { break; }
	}
	return ret;
}

template<class T = int>
vector<T> Read(int n) {
	vector<T> ret(n);
	for (int i = 0; i < n; i++) {
		cin >> ret[i];
	}
	return ret;
}

template<int N = 1'000'000>
class COutBuff
{
public:
	COutBuff() {
		m_p = puffer;
	}
	template<class T>
	void write(T x) {
		int num[28], sp = 0;
		if (x < 0)
			*m_p++ = '-', x = -x;

		if (!x)
			*m_p++ = 48;

		while (x)
			num[++sp] = x % 10, x /= 10;

		while (sp)
			*m_p++ = num[sp--] + 48;
		AuotToFile();
	}
	void writestr(const char* sz) {
		strcpy(m_p, sz);
		m_p += strlen(sz);
		AuotToFile();
	}
	inline void write(char ch)
	{
		*m_p++ = ch;
		AuotToFile();
	}
	inline void ToFile() {
		fwrite(puffer, 1, m_p - puffer, stdout);
		m_p = puffer;
	}
	~COutBuff() {
		ToFile();
	}
private:
	inline void AuotToFile() {
		if (m_p - puffer > N - 100) {
			ToFile();
		}
	}
	char  puffer[N], * m_p;
};

template<int N = 1'000'000>
class CInBuff
{
public:
	inline CInBuff() {}
	inline CInBuff<N>& operator>>(char& ch) {
		FileToBuf();
		ch = *S++;
		return *this;
	}
	inline CInBuff<N>& operator>>(int& val) {
		FileToBuf();
		int x(0), f(0);
		while (!isdigit(*S))
			f |= (*S++ == '-');
		while (isdigit(*S))
			x = (x << 1) + (x << 3) + (*S++ ^ 48);
		val = f ? -x : x; S++;//忽略空格换行		
		return *this;
	}
	inline CInBuff& operator>>(long long& val) {
		FileToBuf();
		long long x(0); int f(0);
		while (!isdigit(*S))
			f |= (*S++ == '-');
		while (isdigit(*S))
			x = (x << 1) + (x << 3) + (*S++ ^ 48);
		val = f ? -x : x; S++;//忽略空格换行
		return *this;
	}
	template<class T1, class T2>
	inline CInBuff& operator>>(pair<T1, T2>& val) {
		*this >> val.first >> val.second;
		return *this;
	}
	template<class T1, class T2, class T3>
	inline CInBuff& operator>>(tuple<T1, T2, T3>& val) {
		*this >> get<0>(val) >> get<1>(val) >> get<2>(val);
		return *this;
	}
	template<class T1, class T2, class T3, class T4>
	inline CInBuff& operator>>(tuple<T1, T2, T3, T4>& val) {
		*this >> get<0>(val) >> get<1>(val) >> get<2>(val) >> get<3>(val);
		return *this;
	}
	template<class T = int>
	inline CInBuff& operator>>(vector<T>& val) {
		int n;
		*this >> n;
		val.resize(n);
		for (int i = 0; i < n; i++) {
			*this >> val[i];
		}
		return *this;
	}
	template<class T = int>
	vector<T> Read(int n) {
		vector<T> ret(n);
		for (int i = 0; i < n; i++) {
			*this >> ret[i];
		}
		return ret;
	}
	template<class T = int>
	vector<T> Read() {
		vector<T> ret;
		*this >> ret;
		return ret;
	}
private:
	inline void FileToBuf() {
		const int canRead = m_iWritePos - (S - buffer);
		if (canRead >= 100) { return; }
		if (m_bFinish) { return; }
		for (int i = 0; i < canRead; i++)
		{
			buffer[i] = S[i];//memcpy出错			
		}
		m_iWritePos = canRead;
		buffer[m_iWritePos] = 0;
		S = buffer;
		int readCnt = fread(buffer + m_iWritePos, 1, N - m_iWritePos, stdin);
		if (readCnt <= 0) { m_bFinish = true; return; }
		m_iWritePos += readCnt;
		buffer[m_iWritePos] = 0;
		S = buffer;
	}
	int m_iWritePos = 0; bool m_bFinish = false;
	char buffer[N + 10], * S = buffer;
};


class CMyST
{
public:
	CMyST(int N) {
		//m_data.assign(N, vector<int>(log2(N) + 2));
		for (int i = 0; i < N; i++) {
			m_data[i][0] = 1;
		}
	}
	template<class _Pr>
	void Init(int N, _Pr& pr) {
		for (int i = 1; i < 22; i++) {
			const int len = 1 << (i - 1);
			for (int j = 0; j < N; j++) {
				if (j + len >= N) { m_data[j][i] = m_data[j][i - 1]; continue; }
				m_data[j][i] = pr(j, j + len, j + 2 * len, m_data[j][i - 1], m_data[j + len][i - 1]);
			}
		}
	}
	template<class _Pr>
	int Query(int left, int len, _Pr& pr) {
		int prer = left;
		int ret = 0;
		for (int i = 0; i < 22; i++) {
			const int mask = 1 << i;
			if (!(len & mask)) { continue; }
			ret = pr(left, prer, prer + (1 << i), ret, m_data[prer][i]);
			prer += (1 << i);
		}
		return ret;
	}
	int m_data[1000'000][22];
};
class Solution {
public:
	vector<int> Ans(vector<int>& a, vector<tuple<int, int, int>>& que) {
		const int N = a.size();
		vector<int> preSum(N + 1);
		vector<int> inxs;
		for (int i = 0; i < N; i++) {
			preSum[i + 1] = preSum[i] + (1 == a[i]);
			if (1 == a[i]) { inxs.emplace_back(i); }
		}
		auto Union = [&](int left, int r, int r2, int s1, int s2) {
			r = min(r, N); r2 = min(r2, N);
			const int c1 = preSum[r2] - preSum[r];
			const int c0 = (r - left) - (preSum[r] - preSum[left]);
			return max(c0 + s2, s1 + c1);
		};
		auto Is01 = [&](int left, int r) {
			auto it = upper_bound(inxs.begin(), inxs.end(), r);
			if (inxs.begin() == it) { return false; }//不存在下标<=r的1
			--it;
			if (*it < left) { return false; }
			auto it2 = lower_bound(inxs.begin(), inxs.end(), left);
			if (it - it2 == *it - left) { return false; }//最后一个1之前没有0
			return true;
		};
		CMyST st(N);
		st.Init(N, Union);
		vector<int> ans;
		for (auto [kind, left, r] : que) {
			left--, r--;
			const int len = r - left + 1;
			if (1 == kind) {
				ans.emplace_back(st.Query(left, len, Union));
			}
			else {
				ans.emplace_back(Is01(left, r) ? 2 : 1);
			}
		}
		return ans;
	}
};
namespace IO {//by cyffff
	int len = 0;
	char ibuf[(1 << 20) + 1], * iS, * iT, out[(1 << 26) + 1];
#define gh() (iS==iT?iT=(iS=ibuf)+fread(ibuf,1,(1<<20)+1,stdin),(iS==iT?EOF:*iS++):*iS++)
#define reg register
	inline int read() {
		reg char ch = gh();
		reg int x = 0;
		reg char t = 0;
		while (ch < '0' || ch>'9')   t |= ch == '-', ch = gh();
		while (ch >= '0' && ch <= '9') x = x * 10 + (ch ^ 48), ch = gh();
		return t ? -x : x;
	}
	inline void putc(char ch) {
		out[len++] = ch;
	}
	template<class T>
	inline void write(T x) {
		if (x < 0)putc('-'), x = -x;
		if (x > 9)write(x / 10);
		out[len++] = x % 10 + 48;
	}
	inline void flush() {
		fwrite(out, 1, len, stdout);
		len = 0;
	}
}
using IO::read;
using IO::write;
using IO::flush;
using IO::putc;

int main() {
#ifdef _DEBUG
	freopen("a.in", "r", stdin);
#endif // DEBUG	
	ios::sync_with_stdio(0); cin.tie(nullptr);
	CInBuff<> in;
	int N,M;
	in >> N >> M;
	auto a = in.Read<int>(N);
	auto que = in.Read<tuple<int, int, int>>(M);
#ifdef _DEBUG		
		printf("N=%d,M=%d", N,M);
		Out(a, "a");
		Out(que, "que=");
		//Out(B, "B=");
#endif // DEBUG			
		
		auto res = Solution().Ans(a,que);		
		for (const auto&i: res) {
			//ob.write(i); ob.write('\n');
			write(i); putc('\n');
		}
		flush();
	return 0;
}

单元测试

cpp 复制代码
	vector<int> a;
		vector<tuple<int, int, int>> que;
		TEST_METHOD(TestMethod01)
		{
			a = { 1,1,1,1 }, que = { {1,1,4} };
			auto res = Solution().Ans(a, que);
			AssertV({4 }, res);
		}
		TEST_METHOD(TestMethod11)
		{
			a={ 0,1,1,0,1,0,0,1 },que = { {1,1,8},{2,1,8},{1,3,6},{2,5,6} };
			auto res = Solution().Ans(a, que);
			AssertV({ 5,2,2,1 }, res);
		}

扩展阅读

我想对大家说的话
工作中遇到的问题,可以按类别查阅鄙人的算法文章,请点击《算法与数据汇总》。
学习算法:按章节学习《喜缺全书算法册》,大量的题目和测试用例,打包下载。重视操作
有效学习:明确的目标 及时的反馈 拉伸区(难度合适) 专注
闻缺陷则喜(喜缺)是一个美好的愿望,早发现问题,早修改问题,给老板节约钱。
子墨子言之:事无终始,无务多业。也就是我们常说的专业的人做专业的事。
如果程序是一条龙,那算法就是他的是睛
失败+反思=成功 成功+反思=成功

视频课程

先学简单的课程,请移步CSDN学院,听白银讲师(也就是鄙人)的讲解。
https://edu.csdn.net/course/detail/38771

如何你想快速形成战斗了,为老板分忧,请学习C#入职培训、C++入职培训等课程
https://edu.csdn.net/lecturer/6176

测试环境

操作系统:win7 开发环境: VS2019 C++17

或者 操作系统:win10 开发环境: VS2022 C++17

如无特殊说明,本算法用**C++**实现。

相关推荐
xh didida2 小时前
C++ --list接口使用及实现
开发语言·c++·list
X journey2 小时前
机器学习实践(18.5):特征工程补充
人工智能·算法·机器学习
Wild_Pointer.2 小时前
项目实战:编写CMakeLists管理Qt+OpenCV项目
开发语言·c++·qt
LG.YDX2 小时前
笔试训练48天:mari和shiny(动态规划 - 线性dp)
数据结构·算法
m0_564876842 小时前
提示词应用
深度学习·学习·算法
qq_283720052 小时前
Transformer 高频面试题及答案
算法·面试·transformer
承渊政道2 小时前
【递归、搜索与回溯算法】(floodfill算法:从不会做矩阵题,到真正掌握搜索扩散思想)
数据结构·c++·算法·leetcode·矩阵·dfs·bfs
黎梨梨梨_2 小时前
C++入门基础(上)(namespace和缺省参数)
开发语言·c++
谭欣辰2 小时前
字典树:高效字符串处理利器
c++·算法