码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-07-30 13:50:54      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:prefix   while   1.0   scanf   rmq   algo   ctime   nbsp   type   

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 + 二分)

标签:prefix   while   1.0   scanf   rmq   algo   ctime   nbsp   type   

原文地址:http://www.cnblogs.com/shinianhuanniyijuhaojiubujian/p/7258721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!