HDU 5806 NanoApe Loves Sequence Ⅱ(双指针)

本文探讨了在给定序列中寻找符合条件的连续子序列数量的问题。通过将关键数值标记为1,其余标记为0的方法,利用双指针技术高效解决区间内第k大数不小于给定值的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<stdio.h>
#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) //当右指针指到n时结束
        {
            while(r<n&&sum<k) //以左指针为基点向右寻找等于k的区间
            {
                r++;
                if(a[r]>=m)
                    sum++;
            }
            if(r==n&&sum<k) //若直到最右端都没有等于k的区间,说明从l到n的sum<k,直接结束
                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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值