hdu 5289 Assignment(尺取)

Assignment

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


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

solution:

我們可以枚舉左端點,然後用ST表和尺取來找出最右邊的端點。

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1e5 + 200;
int dpmax[maxn][20], dpmin[maxn][20],mm[maxn];
int a[maxn],n;
void init()
{
    mm[0] = -1;
    for (int i = 1; i <= n; i++)
    {
        mm[i] = ((i&(i - 1)) == 0) ? mm[i - 1] + 1 : mm[i - 1];
        dpmax[i][0] = dpmin[i][0] = a[i];
    }
    for (int j = 1; j <= mm[n]; j++)
        for (int i = 1; i + (1 << j) - 1 <= n; i++)
        {
        dpmax[i][j] = max(dpmax[i][j - 1], dpmax[i + (1 << (j - 1))][j - 1]);
        dpmin[i][j] = min(dpmin[i][j - 1], dpmin[i + (1 << (j - 1))][j - 1]);
        }
}
int rmq(int x, int y)
{
    int k = mm[y - x + 1];
    return max(dpmax[x][k], dpmax[y - (1 << k) + 1][k]) - min(dpmin[x][k], dpmin[y - (1 << k) + 1][k]);
}
int main()
{
    int k, t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d%d", &n, &k);
        for (int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        init();
        long long ans = 0;
        int l = 1;
        for (int i = 1; i <= n; i++)
        {
            while (rmq(l, i) >= k&&l < i)l++;
            ans += (i - l + 1);
        }
        printf("%I64d\n", ans);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章