Mitsuha_的博客

Rush to the dead summer

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

链接:https://www.nowcoder.com/acm/contest/102/C

时间限制:C/C++ 3秒,其他语言6秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

 We define 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 find the value of the kth largest interval?

输入描述:

The first line contains an integer number T, the number of test cases. 
For each test case : 
The first 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.
示例1

输入

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.

思路:比较裸的二分+尺取的题目。二分枚举第k大的值,尺取判断有多少个区间的价值大于等于k,依次改变上下界。

#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;
}





阅读更多
版权声明:http://blog.csdn.net/Mitsuha_。 https://blog.csdn.net/Mitsuha_/article/details/79945637
个人分类: 二分+尺取
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭