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
 

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
#include
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;
}


你可能感兴趣的:(HDU,数据结构,杂题,尺取,ST表)