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

Posted 十年换你一句好久不见

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了玲珑杯 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\n",ans);
    return 0;
}

 

以上是关于玲珑杯 Round 19 B Buildings (RMQ + 二分)的主要内容,如果未能解决你的问题,请参考以下文章

“玲珑杯”ACM比赛 Round #19 B -- Buildings

玲珑杯”ACM比赛 Round #19 B 维护单调栈

“玲珑杯”ACM比赛 Round #19题解&源码A,规律,B,二分,C,牛顿迭代法,D,平衡树,E,概率dp

“玲珑杯”ACM比赛 Round #19

玲珑杯 Round 19 A simple math problem

玲珑杯 round18 A 计算几何瞎暴力