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

【题意】 给出一排n个数,求存在多少个区间使得区间内第k大的数不小于m。

【解题思路】 可以将所有不小于m的数看作1,其余为0,只要区间内的和不小于k则成立。此处可以使用双指针。

【AC代码】

#include
#define fff 200005
using namespace std;
int a[fff];
int main()
{
    int t,n,m,k,i;
    scanf("%d",&t);
    while(t--)
    {
        __int64 ans=0;
        int l=1,r=0,sum=0; //初始化左指针指向1,右指针指向0
        scanf("%d%d%d",&n,&m,&k);
        for(i=1;i<=n;i++)
            scanf("%d",&a[i]);
        while(r//当右指针指到n时结束
        {
            while(rsum//以左指针为基点向右寻找等于k的区间
            {
                r++;
                if(a[r]>=m)
                    sum++;
            }
            if(r==n&&sum//若直到最右端都没有等于k的区间,说明从l到n的sum
                break;
            if(sum==k) //若sum==k,则加上后面的区间,sum>=k,一样成立
                ans+=n-r+1;
            //左指针向右移动,观察a[l]是否不小于m,以此来改变sum和ans的值
            while(sum==k) 
            {
                if(a[l]>=m)
                    sum--;
                if(sum==k)
                    ans+=n-r+1;
                l++;
            }
        }
        printf("%I64d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(双指针)