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
A
1
,
A
2
,...,
A
n
, denoting the elements of the sequence.
1≤T≤10, 2≤n≤200000, 1≤k≤n/2, 1≤m,
A
i
≤
10
9
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
题目大意:
计算有多少个区间的第 k 大数不小于 m,当然这个区间至少要 k 个数。
解题思路:
法1:用前缀和保存前i个区间有多少不小于 m 的数,左端点for过去,然后二分右端点,如果分到某个右端点恰好满足(l ,r)中的第 k 个数小于 m,那么右端点右边的区间都符合。
ac代码:
#include
using namespace std;
typedef long long ll;
ll sum[200005],a[200005],n,m,k;
int check(ll l,ll r){
if(sum[r]-sum[l-1]>=k)
return true;
else
return false;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
memset(sum,0,sizeof(sum));
int i;
scanf("%d%d%d",&n,&m,&k);
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
sum[i]+=sum[i-1]+(a[i]>=m?1:0);
}
ll ans=0;
for(i=1;i<=n-k+1;i++){
ll l=i+k-1,r=n;
while(l+1
ll mid=(l+r)/2;
if(check(i,mid)){
r=mid;
}
else
l=mid;
}
if(check(i,l))
ans+=n-l+1;
else if(check(i,r))
ans+=n-r+1;
}
printf("%lld\n",ans);
}
return 0;
}
法2:尺取法。
ac代码:
#include
using namespace std;
typedef long long ll;
ll sum[200005],a[200005];
ll k;
int check(ll l,ll r){
if(sum[r]-sum[l-1]>=k)
return 1;
else
return 0;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
memset(sum,0,sizeof(sum));
ll n,i;
ll m;
scanf("%lld%lld%lld",&n,&m,&k);
for(i=1;i<=n;i++){
scanf("%lld",&a[i]);
sum[i]=sum[i-1]+(a[i]>=m?1:0);
}
ll ans=0;
ll j=1;
i=1;
while(i<=n&&j<=n){
if(check(i,j)){
ans+=n-j+1;
i++;
}
else{
j++;
}
}
printf("%lld\n",ans);
}
return 0;
}