跳到正文

个人记录

【2026rdfxyd】上课笔记-单调队列与单调栈0523

rdrding约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年7月10日
更新
2026年7月10日
篇幅
约 5 分钟

版本

  1. v1当前

T1

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 8e4+10;
int n,a[N],q[N],t=0;
long long ans;
int main(){
	
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	for(int i=1;i<=n;i++){
		if(t<1)q[t++]=i;
		else{
			while(t>=1 && a[q[t-1]] <= a[i]){
				t--;
			}
			ans+=t;
			q[t++]=i;
		}
	}
	printf("%lld\n",ans);
	
	return 0;
}

T2 用单调栈解决离线RMQ

题目

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10,M=2e6+10;
int n,m,a[N],ans[M],st[N],top;
vector<pair<int,int> > q[M];
inline int read()
{
	int x=0,f=1;char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
	return x*f;
}
int main(){
	
	n=read(),m=read();
	for(int i=1;i<=n;i++){
		a[i]=read();
	}
	for(int i=1,l,r;i<=m;i++){
		l=read(),r=read();
		q[r].push_back(make_pair(l,i));
	}
	for(int i=1;i<=n;i++){
		while(top && a[st[top]] <= a[i])top--;
		st[++top]=i;
		for(pair<int,int> x:q[i]){
			int id=lower_bound(st+1,st+top+1,x.first)-st;
			ans[x.second]=a[st[id]];
		}
	}
	for(int i=1;i<=m;i++){
		printf("%d\n",ans[i]);
	}
	
	return 0;
}

T3

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int n,d,h1,h2,t1=-1,t2=-1,q1[N],q2[N];
int ans=1e9;
struct node{
	int x,y;
}a[N];
bool cmp(node a,node b){
	return a.x < b.x;
}
int main(){
	
	scanf("%d %d",&n,&d);
	for(int i=1;i<=n;i++){
		scanf("%d %d",&a[i].x,&a[i].y);
	}
	sort(a+1,a+n+1,cmp);
	for(int l=1,r=0;l<=n;l++){
		while(h1 <= t1 && q1[h1] < l)h1++;
		while(h2 <= t2 && q2[h2] < l)h2++;
		while(a[q1[h1]].y-a[q2[h2]].y < d && r < n){
			r++;
			while(h1 <= t1 && a[q1[t1]].y < a[r].y)t1--;
			while(h2 <= t2 && a[q2[t2]].y > a[r].y)t2--;
			q1[++t1]=r;
			q2[++t2]=r;
		}
		if(a[q1[h1]].y - a[q2[h2]].y >= d)ans=min(ans,a[r].x-a[l].x);
	}
	printf("%d\n",ans==1e9?-1:ans);
	
	return 0;
}

T4

先进行前缀和,考虑右端点,求出[r-m+1,r-1]的最小值

T5

[T6]

二分答案 分割代价,连续的分数段之和 <= mid,

s[i-1]-s[j]<=mid

f[i]=f[j]+a[i]

[T7]

向左边与右边找到最斜的直线

找到最大的 hi/∣xi−p∣h_i / |x_i - p|

维护凸包,斜率递减

利用凹凸性二分

[T8]

对于每个柱子找到左右第一个比他矮的柱子

T9

原文