hdu 5806 NanoApe Loves Sequence Ⅱ

来源:互联网 发布:c语言数组长度最大多少 编辑:程序博客网 时间:2024/05/29 19:27

题目链接:hdu 5806

NanoApe Loves Sequence Ⅱ

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/131072 K (Java/Others)

Problem Description
NanoApe, the Retired Dog, has returned back to prepare for for the National Higher Education Entrance Examination!

In math class, NanoApe picked up sequences once again. He wrote down a sequence with n numbers and a number m on the paper.

Now he wants to know the number of continous subsequences of the sequence in such a manner that the k-th largest number in the subsequence is no less than m.

Note : The length of the subsequence must be no less than k.

Input
The first line of the input contains an integer T, denoting the number of test cases.

In each test case, the first line of the input contains three integers n,m,k.

The second line of the input contains n integers A1,A2,…,An, denoting the elements of the sequence.

1≤T≤10, 2≤n≤200000, 1≤k≤n/2, 1≤m,Ai≤109

Output
For each test case, print a line with one integer, denoting the answer.

Sample Input
1
7 4 2
4 2 7 7 6 5 1

Sample Output
18

比赛的时候真是太不冷静了……第二天早上一下就想出来了。实现水平不行,调试还是费了点时间。int又炸。

看题面直接暴力妥妥的TLE,所以考虑降低复杂度。
设一个p记录此时子串的第一个元素的下标,i则为此子串的最后一个元素的下标。模拟出队入队。

设一个cnt记录当前选中的子串中比m大的数的个数,一开始先使新元素入队,直到cnt == k时ans就加上n - i(正好为以现在选中的子串为前缀的子串的数量),然后考虑p1后移,以选中新的子串,如果arr[p1] < m,那么它出队不会使第k大的数发生变化,我们使p1++,此时形成了一个新的子串,因此ans要再次加n - i,如此重复直到arr[p1] >= m为止。

如果一开始arr[p1] >= m,就直接使p1++,cnt- -,第一个元素出队。

当元素出队到cnt < k时,再使后面的元素依次入队。

#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>#define MAX 200005#define mod 1000000007#define INF -0x3f3f3f3fusing namespace std;int arr[MAX];int main(){    int T;    scanf("%d", &T);    while(T--)    {        long long int n, m, i = 0ll;        int k;        scanf("%I64d %I64d %d", &n, &m, &k);        for(; i < n; i++)        {            scanf("%d", &arr[i]);        }        int cnt = 0, p1 = 0;        long long int ans = 0;        for(i = 0ll; i < n; i++)        {            if(cnt == k)                break;            else if(arr[i] >= m)                cnt++;        }        i--;        while(i < n)        {            //printf("i:%d\n", i);            if(cnt == k)            {                ans += n - i;                //printf("ans1:%d\n", ans);                while(arr[p1] < m)//满足此条件时第一个元素出队不会影响第k大的值。                {                    p1++;                    ans += n - i;                    //printf("ans2:%d\n", ans);                }                p1++;                cnt--;                //printf("%d\n", p1);            }            else            {                i++;//cnt < k时,i后移使新元素入队。                if(arr[i] >= m)                    cnt++;            }        }        printf("%I64d\n", ans);    }    return 0;}

运行结果:
这里写图片描述

0 0