跳到正文

题解

唐熙程的题解5

junnanzai约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

错题:

T628213 值轮兵团站岗

错误原因:

去死嗑前面的题了,这题题目都没看。

正确思路:

这道题我们可以运用于队列相关的知识做。

先定义一个队头( headhead )、队尾( tailtail ), headhead 要从0开始0开始, tailtail 在−1-1结束。

C++
int head=0,tail=-1,w;

然后创建队列并进行排序。

C++
for(int i=1;i<=n;i++){
  cin>>w;
  a[++tail]=w;
}
sort(a+head,a+tail+1);//注意这里的结点不是tail,而是tail+1。

然后可以用 whilewhile 循环来做 mm 次操作。

C++
while(m--)//这里的的范围是3e5*3e5=9e10,不会超时。

接下来是三种操作,但在之前,我们可以定义一个标记变量 tt ,方便记录 xx 的总量。

C++
int t=0;

·当 opt=1opt=1 :

C++
if(opt==1){
	cin>>x;
	t+=x;
	while(a[tail]+t>k && tail-head>-1){//这里表示当队列不为空时才会去减人数。
		tail--;
	}
}

·当 opt=2opt=2 :

C++
if(opt==2){
	cin>>x;
	t-=x;
	while(a[head]+t<-k && tail-head>-1){//与上面同理。
		head++;
	}
}

·当 opt=3opt=3 :

C++
if(opt==3){
	cout<<tail-head+1<<'\n';
}

三种情况都做完了,但还有一个小细节,就是数据范围。 1≤n,m≤3×10e51≤n,m≤3×10e5 1≤k,x≤2×10e91≤k,x≤2×10e9 用 intint ,肯定会超,所以得开 longlonglong long 。

正确代码:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=3e5+5;
long long n,m,k,opt,x;
long long a[N],head=0,tail=-1,w;
int main(){
	cin>>n>>m>>k;
	for(int i=1;i<=n;i++){
		cin>>w;
		a[++tail]=w;
	}
	sort(a+head,a+tail+1);
	long long t=0;
	while(m--){
		cin>>opt;
		if(opt==1){
			cin>>x;
			t+=x;
			while(a[tail]+t>k && tail-head>-1){
				tail--;
			}
		}
		if(opt==2){
			cin>>x;
			t-=x;
			while(a[head]+t<-k && tail-head>-1){
				head++;
			}
		}
		if(opt==3){
			cout<<tail-head+1<<'\n';
		}
	}
	return 0;
}
原文