# Codeforces Round #333 (Div. 2) B. Approximating a Constant Range ---- 尺取+树状数组（区间最值）

AC代码：

``````#include<bits/stdc++.h>
#define IO          ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define pb(x)       push_back(x)
#define sz(x)       (int)(x).size()
#define sc(x)       scanf("%d",&x)
#define pr(x)       printf("%d\n",x)
#define abs(x)      ((x)<0 ? -(x) : x)
#define all(x)      x.begin(),x.end()
#define mk(x,y)     make_pair(x,y)
#define debug       printf("!!!!!!\n")
#define fin         freopen("in.txt","r",stdin)
#define fout        freopen("out.txt","w",stdout)
using namespace std;
typedef long long ll;
const int mod = 1e9+7;
const double PI = 4*atan(1.0);
const int maxm = 1e8+5;
const int maxn = 2e5+5;
const int INF = 0x3f3f3f3f;
const ll LINF = 1ll<<62;
int c1[maxn],c2[maxn],a[maxn];
inline int lowbit(int x){return x&(-x);}
void update1(int x,int n) //log^2(n)
{
for(int i=x;i<=n;i+=lowbit(i))
{
c1[i] = a[i];
for(int j=1;j<lowbit(i);j<<=1) c1[i] = max(c1[i],c1[i-j]);
}
}
int query1(int l,int r) //log(n)
{
int ans = -1;
while(r>=l)
{
ans = max(ans,a[r]);
r--;
for(;r-lowbit(r)>=l;r-=lowbit(r)) ans = max(ans,c1[r]);
}
return ans;
}
void update2(int x,int n) //log^2(n)
{
for(int i=x;i<=n;i+=lowbit(i))
{
c2[i] = a[i];
for(int j=1;j<lowbit(i);j<<=1) c2[i] = min(c2[i],c2[i-j]);
}
}
int query2(int l,int r) //log(n)
{
int ans = INF;
while(r>=l)
{
ans = min(ans,a[r]);
r--;
for(;r-lowbit(r)>=l;r-=lowbit(r)) ans = min(ans,c2[r]);
}
return ans;
}
int main()
{
//fin;
IO;
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
update1(i,n);
update2(i,n);
}
int ans = 0;
for(int l=1,r=1;r<=n;r++)
{
while(query1(l,r)-query2(l,r)>1) l++;
ans = max(ans,r-l+1);
}
cout<<ans<<endl;
return 0;
}
``````

原文作者：B树
原文地址: https://blog.csdn.net/m0_37624640/article/details/82869643
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。