玲珑杯 Round 19 B Buildings (RMQ + 二分)

DESCRIPTION

There are nn buildings lined up, and the height of the ii-th house is hihi.

An inteval [l,r][l,r](lr)(l≤r) is harmonious if and only if max(hl,,hr)min(hl,,hr)kmax(hl,…,hr)−min(hl,…,hr)≤k.

Now you need to calculate the number of harmonious intevals.

INPUT
The first line contains two integers n(1n2×105),k(0k109)n(1≤n≤2×105),k(0≤k≤109). The second line contains nn integers hi(1hi109)hi(1≤hi≤109).
OUTPUT
Print a line of one number which means the answer.
SAMPLE INPUT
3 1 1 2 3
SAMPLE OUTPUT
5
HINT
Harmonious intervals are: [1,1],[2,2],[3,3],[1,2],[2,3][1,1],[2,2],[3,3],[1,2],[2,3].
RMQ+二分
//Round 19 B;
#include <iostream> 
#include <algorithm> 
#include <cstring> 
#include <cstdio>
#include <vector> 
#include <queue> 
#include <cstdlib> 
#include <iomanip>
#include <cmath> 
#include <ctime> 
#include <map> 
#include <set> 
using namespace std; 
#define lowbit(x) (x&(-x)) 
#define max(x,y) (x>y?x:y) 
#define min(x,y) (x<y?x:y) 
#define MAX 100000000000000000 
#define MOD 1000000007
#define pi acos(-1.0) 
#define ei exp(1) 
#define PI 3.141592653589793238462
#define INF 0x3f3f3f3f3f 
#define mem(a) (memset(a,0,sizeof(a))) 
typedef long long ll; 
int maxn[200005][25],minn[200005][25];
int a[200005];
int n,k,x;
void get_rmq()
{
    for(int i=1;i<=n;i++)
    {
        maxn[i][0]=a[i];
        minn[i][0]=a[i];
    }
    for(int j=1;(1<<j)<=n;j++)
    {
        for(int i=1;i+(1<<j)-1<=n;i++)
        {
            maxn[i][j]=max(maxn[i][j-1],maxn[i+(1<<(j-1))][j-1]);
            minn[i][j]=min(minn[i][j-1],minn[i+(1<<(j-1))][j-1]);
        }
    }
}
bool rmq(int l,int r)
{
    if(l>r) return 0;
    int f=int(log((double)(r-l+1))/log(2.0));
    return max(maxn[l][f],maxn[r-(1<<f)+1][f])-min(minn[l][f],minn[r-(1<<f)+1][f])<=k;
}
int main() 
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    get_rmq();
    ll ans=0;
    for(int i=1;i<=n;i++)
    {
        int l=1,r=i,mid,pos=i;
        while(l<=r)
        {
            mid=(l+r)>>1;
            if(rmq(mid,i)) r=mid-1,pos=mid;
            else l=mid+1;
        }
        ans+=i-pos+1;
    }
    printf("%lld
",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/shinianhuanniyijuhaojiubujian/p/7258721.html