牛客网【每日一题】4月22日 K-th Number

K-th Number

https://ac.nowcoder.com/acm/problem/14301

链接:

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 65536K,其他语言131072K
64bit IO Format:%lld

题目描述

Alice are given an array A[1..N] with N numbers. Now Alice want to
build an array B by a parameter K as following rules: Initially, the
array B is empty. Consider each interval in array A. If the length of
this interval is less than K, then ignore this interval. Otherwise,
find the K-th largest number in this interval and add this number into
array B. In fact Alice doesn't care each element in the array B. She
only wants to know the M-th largest element in the array B. Please
help her to fi nd this number.

输入描述:

The first line is the number of test cases. For each test case,
the first line contains three positive
numbers N(1≤N≤105);K(1≤K≤N);M. The second line contains N numbers
Ai(1≤Ai≤109). It's guaranteed that M is not greater than the length of
the array B.

输出描述:

For each test case, output a single line containing the M-th largest
element in the array B.

示例1
输入

2
5 3 2
2 3 1 5 4
3 3 1
5 8 2

输出

3
2

题解:

求:将A的每个区间求第K大值,并放入B中,然后再求B的第M大值

我怎么也想不到用二分。。。
我们首先要通过二分来得到一个x,这个x用于限制区间中第K大的数的数量。什么意思?
我们假设最后结果是x,也就是x是最后B中第m大的数
还有m-1个数比x大,而在m-1个数是从A中部分区间选出的第K大的数,那我们只需要选出这些区间就足够了,并不需要全部选出。换句话说,我们去得到第K大数,此数大于x的区间一共有多少个,我们需要m-1个,(因为数字x是第m个),如果我们得到的区间不是m-1个,比m-1大,说明你的x取小了,导致更多不符合我们要求的区间被选进,如果小于m-1,则相反。
这个过程我们可以通过二分+尺取来实现

第k大的数大于x的区间的数量求法:
满足条件的数组中,至少应该有k个数大于x,那枚举区间左界L时,我们可以直接从L出发向右扫描看看有多少大于x的数,当大于x的数正好满足k个时,将这个位置记为R,在当前位置R再往右扫描,大于x的数只会比k多不会比k少,也就是R之后的数与其组成连续区间的话都是符合条件的(此处有n-R+1个)。那我们将L向右移动,R也必须向右移动,才能保准k的数量。
每次二分一个x,都经过上述过程
二分+尺取 复杂度是O(nlogn)

代码:

如果有点乱,来看看代码

/* 
2  3 1 5 4


2 3 1 5 
2 3 1 5 4

3 1 5 4

2 3 3
*/

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;

const int manx=2e6+2;
const int INF=1e9+4;
ll a[manx];

ll n,m,k,cnt,sum; 
ll check(ll x){
    ll l,r;
    l=1,r=0,cnt=0,sum=0;
    while(l<=n){
        while(r<n&&cnt<k) if(a[++r]>=x) cnt++;
        if(cnt==k) sum+=n-r+1;
        if(a[l]>=x) cnt--;
        l++;
    }
    return sum>=m;
}

int main(){
    ll t,l,r;
    cin>>t;
    while(t--){
        cin>>n>>k>>m;
        for(int i=1;i<=n;i++) 
        cin>>a[i];
        l=1,r=INF;
        while(l+1<r)
        {
            ll mid= l+r >>1;
            if(check(mid)) l=mid;
            else r=mid;
        }
        cout<<l<<endl;
    }
    return 0;
}
全部评论

相关推荐

02-22 20:28
重庆大学 Java
程序员牛肉:首先不要焦虑,你肯定是有希望的。 首先我觉得你得好好想一想自己想要什么。找不到开发岗就一定是失败的吗?那开发岗的35岁危机怎么说?因此无论是找工作还是考公我觉得你都需要慎重的想一想。但你一定要避开这样一个误区:“我是因为找不到工作所以不得不选择考公”。 千万不要这么想。你这个学历挺好的了,因此你投后端岗肯定是有面试机会的。有多少人简历写的再牛逼,直接连机筛简历都过不去有啥用?因此你先保持自信一点。 以你现在的水平的话,其实如果想要找到暑期实习就两个月:一个月做项目+深挖,并且不断的背八股。只要自己辛苦一点,五月份之前肯定是可以找到暑期实习的,你有点太过于高看大家之间的技术差距了。不要焦虑不要焦虑。 除此之外说回你这个简历内容的话,基本可以全丢了。如果想做后端,先踏踏实实做两个项目再说+背八股再说。如果想考公,那就直接备战考公。 但是但是就像我前面说的:你考公的理由可以是因为想追求稳定,想追求轻松。但唯独不能是因为觉得自己找不到工作。不能这么小瞧自己和自己的学历。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务