hdoj 5289 Assignment 【RMQ + 二分查找区间最优长度】

Assignment

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


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
 

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]
 

题意:有N个员工,编号从1到N,已经给出每个员工的能力值。现在要把他们分组,要求每一组成员的编号是连续的且这一组里面最大能力值与最小能力值相差必须小于Q。问你可以分成多少组。

首先我们要知道:若以a 为区间左端点,求出满足条件的最大区间右端点为b,那么在[a,b]区间可以分成b - a + 1组。(分别为[a,a] 、 [a,a+1]、...、[a,b])


思路:
一,先RMQ求出区间的最大值、最小值。
二,从1到N遍历,每次以遍历点 i 为区间左端点,找到能够满足的最大区间右端点R,累加R - i + 1即可。这里使用了二分法,但终止条件 和 更替区间有些不同。


AC代码:786ms

#include 
#include 
#include 
#define LL long long
#define MAXN 100000+10
using namespace std;
int A[MAXN];
int Amax[MAXN][20];
int Amin[MAXN][20];
int N, Q;
void RMQ_init()
{
    for(int i = 1; i <= N; i++)
        Amax[i][0] = Amin[i][0] = A[i];
    for(int j = 1; (1< 1)//只要两个数相邻或者两个数相等
            {
                mid = (left + right) >> 1;
                //因为判断的是整个区间是否合法 
                //所以区间不合法不代表端点不合法
                if(query(i, mid) >= Q)
                    right = mid;//不能去掉区间的端点
                else
                    left = mid;//不能去掉区间的端点
            }
            //搜到 right - left <= 1为止
            if(query(i, right) < Q)//至少有一个满足
                ans += right - i + 1;
            else
                ans += left - i + 1;
        }
        printf("%lld\n", ans);
    }
    return 0;
}

网上还有一种很巧的方法

#include 
#include 
#include 
#define LL long long
#define MAXN 100000+10
using namespace std;
int A[MAXN];
int Amax[MAXN][20];
int Amin[MAXN][20];
int N, Q;
void RMQ_init()
{
    for(int i = 1; i <= N; i++)
        Amax[i][0] = Amin[i][0] = A[i];
    for(int j = 1; (1<= Q&& s < i)
                s++;
            ans += i - s + 1;
        }
        printf("%lld\n", ans);
    }
    return 0;
}


你可能感兴趣的:(二分,RMQ)