hdu5289||2015多校联合第一场1002贪心+RMQ

http://acm.hdu.edu.cn/showproblem.php?pid=5289

Problem Description
Tom owns a company and he is the boss. There are n staffs which are numbered from 1 to n in this company, and every staff has a ability. Now, Tom is going to assign a special task to some staffs who were in the same group. In a group, the difference of the ability of any two staff is less than k, and their numbers are continuous. Tom want to know the number of groups like this.
 

Input
In the first line a number T indicates the number of test cases. Then for each case the first line contain 2 numbers n, k (1<=n<=100000, 0<k<=10^9),indicate the company has n persons, k means the maximum difference between abilities of staff in a group is less than k. The second line contains n integers:a[1],a[2],…,a[n](0<=a[i]<=10^9),indicate the i-th staff’s ability.
 

Output
For each test,output the number of groups.
 

Sample Input
   
   
   
   
2 4 2 3 1 2 4 10 5 0 3 4 5 2 1 6 7 8 9
 

Sample Output
   
   
   
   
5 28
Hint
First Sample, the satisfied groups include:[1,1]、[2,2]、[3,3]、[4,4] 、[2,3]
 

Source
2015 Multi-University Training Contest 1

/**
hdu5289||2015多校联合第一场1002贪心+RMQ
题目大意:找出连续子区间,其最大最小值只差小于k
解题思路:用rmq维护区间最大最小值只差,贪心扫一遍即可,复杂度O(nlogn)
*/
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
using namespace std;
const int N=200005;
int a[N],n,m;
int dp1[N][30];
int dp2[N][30];

void RMQ_init(int n)
{
    for(int i=1;i<=n;i++)
    {
        dp1[i][0]=a[i];
        dp2[i][0]=a[i];
    }
    for(int j=1;(1<<j)<=n;j++)
    {
        for(int i=1;i+(1<<j)-1<=n;i++)///白书上的模板,次行稍作改动,否则dp数组要扩大一倍防止RE
        {
            dp1[i][j]=max(dp1[i][j-1],dp1[i+(1<<(j-1))][j-1]);
            dp2[i][j]=min(dp2[i][j-1],dp2[i+(1<<(j-1))][j-1]);
        }
    }
}

int rmq(int x,int y)
{
    int k=0;
    while((1<<(k+1))<=y-x+1)k++;
    return max(dp1[x][k],dp1[y-(1<<k)+1][k])-min(dp2[x][k],dp2[y-(1<<k)+1][k]);
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        RMQ_init(n);
        int k=1;
        long long sum=0;
        for(int i=1;i<=n;i++)
        {
            while(rmq(k,i)>=m&&k<i)k++;
            sum+=(i-k+1);
           // printf("dis i k i-k+1:%d %d %d %d\n",rmq(k,i),i,k,i-k+1);
        }
        printf("%I64d\n",sum);
    }
    return 0;
}


你可能感兴趣的:(hdu5289||2015多校联合第一场1002贪心+RMQ)