# 长安大学第三届ACM-ICPC程序设计竞赛（同步赛）-C：The K-th Largest Interval（二分+尺取）

64bit IO Format: %lld

## 题目描述

We deﬁne a value of an interval is the second largest number of it's elements, and of course an interval has at least two elements.
Given an array A with n elements and a number k, can you ﬁnd the value of the kth largest interval?

## 输入描述:

The ﬁrst line contains an integer number T, the number of test cases.
For each test case :
The ﬁrst line contains two integer numbers n,k(2 ≤ n ≤ 105,1 ≤ k ≤ n(n−1)/2), the number of test cases.
The second lines contains n integers Ai(1 ≤ Ai ≤ 109), the elements of array A.

## 输出描述:

For each test case print the value of the kth largest interval.

## 输入

2
3 3
1 2 3
5 1
1 2 2 3 3

## 输出

1
3

## 说明

For the sample input, there are three intervals.
Interval [1 2 3] has value 2.
Interval [2 3] has value 2.
Interval [1 2] has value 1.
So the 3rd largest interval is [1 2] whose value is 1.

#include<bits/stdc++.h>
using namespace std;
const int MAX=1e5+30;
const int MOD=1e9+7;
const double PI=acos(-1);
typedef  long long ll;
int a[MAX],n;
ll check(int x)
{
deque<int>p;
ll ans=0,last=0;
for(int i=1;i<=n;i++)
{
if(a[i]>=x)p.push_front((ll)i);
if(p.size()>=2)
{
ans+=(p.back()-last)*(n-i+1);
last=p.back();
p.pop_back();
}
}
return ans;
}
int main()
{
int T;
cin>>T;
while(T--)
{
ll k;
scanf("%d%lld",&n,&k);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
int l=1,r=1e9,ans=0;
while(r>=l)
{
int m=(l+r)/2;
if(check(m)>=k)
{
ans=m;
l=m+1;
}
else r=m-1;
}
printf("%d\n",ans);
}
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120