跳到正文

算法·理论

题解:P5724 【深基4.习5】求极差 / 最大跨度值 / 最大值和最小值的差

Accepted_MAXN约 3 分钟
原文

这是 2026年2月20日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年2月20日
更新
2026年2月24日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

做法:大炮打蚊子 或 手就捏死蚊子。

水题。

思路

本题两种解决方案:

11. 按照题目模拟,适合新手、蒟蒻等。

22. 线段树,适合闲的没事干的、大佬等,对新人极不友好。

11 . AC code 手就捏死蚊子方案
C++
#include<bits/stdc++.h>
using namespace std;
int n,maxx,minn=1001,x;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>x;
        if(x>maxx)maxx=x;
        if(x<minn)minn=x;
    }
    cout<<maxx-minn;
}
22 . AC code 大炮打蚊子方案
C++
#include<bits/stdc++.h>
using namespace std;
const int maxn = 105;
int n,a[maxn],tree_max[405],tree_min[405];
void find_max(int rt,int left,int right){
	if(left==right){
		tree_max[rt]=a[left];
		return;
	}
	int mid=left+(right-left)/2;
	find_max(2*rt,left,mid);
	find_max(2*rt+1,mid+1,right);
	tree_max[rt]=max(tree_max[2*rt],tree_max[2*rt+1]);
}
void find_min(int rt,int left,int right){
	if(left==right){
		tree_min[rt]=a[left];
		return;
	}
	int mid=left+(right-left)/2;
	find_min(2*rt,left,mid);
	find_min(2*rt+1,mid+1,right);
	tree_min[rt]=min(tree_min[2*rt],tree_min[2*rt+1]);
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];
	find_max(1,1,n);
    find_min(1,1,n);
    cout<<tree_max[1]-tree_min[1];
    return 0;
}

建议大家用第一种方案,不仅简洁,时间、空间复杂度也小,速度还快,第二种方案仅供娱乐。

本文章解释权归 Accepted_MAXN 所有。