HDU 5289 Assignment(RMQ+二分)

来源:互联网 发布:俄国史教程 知乎 编辑:程序博客网 时间:2024/05/17 03:35

Assignment

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3338    Accepted Submission(s): 1549


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
24 23 1 2 410 50 3 4 5 2 1 6 7 8 9
 

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

Author
FZUACM
 

Source
2015 Multi-University Training Contest 1
 

Recommend

We have carefully selected several similar problems for you:  5717 5716 5715 5714 5713 



代码:

#include<stdio.h>#include<string.h>#include<algorithm>#include<cmath>using namespace std;int maxn[100000][30];int minn[100000][30];int a[100000];int n,k;void RMQ_init(){    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]);        }    }}int query(int l,int r){    int k=log2(r-l+1);    return max(maxn[l][k],maxn[r-(1<<k)+1][k])-min(minn[l][k],minn[r-(1<<k)+1][k]);}int main(){    int t;    scanf("%d",&t);    while(t--)    {        scanf("%d%d",&n,&k);        for(int i=1;i<=n;i++)        {            scanf("%d",&a[i]);            maxn[i][0]=minn[i][0]=a[i];        }        RMQ_init();        long long ans=0;        int l,r;        for(int i=1;i<=n;i++)        {            l=i,r=n;            while(l<=r)            {                int mid=(l+r)/2;                int cha=query(i,mid);                if(cha<k)l=mid+1;                else r=mid-1;            }            ans=ans+l-i;        }        printf("%lld\n",ans);    }}


0 0
原创粉丝点击