改题目解析在上一篇点击打开链接
这里使用了map来实现同样的过程,做上下界的查找,map内直接存的就是一个个对应的区间,对于所有的<key,value>对,map默认按key值升序排序,这样,可以将区间以<l , r>的形式存储,会以l升序排序。
对于lower_bound 和 uppper_bound进行说明:
// lower_bound 第一个大于或者等于查找值的位置
// upper_bound 第一个大于查找值的位置
// begin() 就是存储的第一单元,end()为虚单元,lower或者upper找不到对应值时,都会跑到end()
(从这两个查询的定义来看,设置一个最后的虚单元是有必要的,代表没有找到结果,而begin没有必要设置成虚单元)
对于二元组,先根据first ,然后根据second排序,最好使用pair这种现成的结构体工具
#include<cstdio>
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<algorithm>
#include<map>
using namespace std;
const int inf = 1e9 + 10;
const int maxn = 1e5+10;
typedef pair<int,int> pii;
pii a[maxn];
map<int,int> ma;
map<int,int> ::iterator it;
int n,count_[maxn],cnt=0;
int main()
{
cin>>n;
for(int i=1;i<=n;i++) scanf("%d",&a[i].first),a[i].second=i;
sort(a + 1, a+1+n);
ma[1] = n;
int ans_seg = 1 , ans_high = a[1].first + 1;
for(int i = n ; i > 1 ; i--){
it = ma.upper_bound(a[i].second); --it;
int u = it->first , v = it->second, m = a[i].second, nval = a[i - 1].first + 1;
--count_[v - u + 1],cnt-=(!count_[v - u + 1]);
ma.erase(it);
if(v > m) {
cnt += (!count_[v - m]);
++count_[v - m];
ma[m + 1] = v;
}
if(m > u){
cnt += (!count_[m - u]);
++count_[m - u];
ma[u] = m - 1;
}
if(cnt == 1 && a[i - 1].first != a[i].first && ma.size() >= ans_seg) {
ans_seg = ma.size();
ans_high = nval;
}
}
cout<<ans_high<<endl;
return 0;
}