跳到正文

题解

题解:AT_awc0001_e 気温の変動幅

ChenHaoQi约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年2月11日
收录
2026年2月12日
更新
2026年11月15日
篇幅
约 2 分钟

版本

  1. v1当前

类似 P1886,其实几乎一样,可以使用单调队列求解。

我们可以用 STL 中的 deque 模拟单调队列,当然也可以手写。使用两个单调队列分别维护最大值和最小值,在每个时刻(窗口)对两值之差取最大值即为所求。需要特别注意 HiH_i 可以小于 00。时间复杂度为 O(N+K)O(N+K),不会超时。

AC代码
C++
#include<iostream>
#include<queue>
#include<climits>
using namespace std;

#define AWC0001_E 0
const int maxn=1e6;
int a[maxn+1];
int n,k,ans=INT_MIN; //ans=0将导致错误。INT_MIN=-2147483648,在 <climits> 中定义

void solve(){
	deque<int> q1,q2;
	for(int i=1; i<=n; i++){
		while(!q1.empty() && a[i]>=a[q1.back()]) q1.pop_back();
		while(!q2.empty() && a[i]<=a[q2.back()]) q2.pop_back();
		q1.push_back(i);
		q2.push_back(i);
		if(i>=k){
			while(!q1.empty() && q1.front()==i-k) q1.pop_front();
			while(!q2.empty() && q2.front()==i-k) q2.pop_front();
		}
		if(i>=k-1) ans=max(ans,a[q1.front()]-a[q2.front()]);
	}
}

signed main(){
	cin>>n>>k;
	for(int i=1; i<=n; i++){
		cin>>a[i];
	}
	solve();
	cout<<ans;
	return AWC0001_E;
}
原文