牛客网【每日一题】4月22日 K-th Number
鏈接:
時間限制: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
輸入
輸出
3 2題解:
求:將A的每個區(qū)間求第K大值,并放入B中,然后再求B的第M大值
我怎么也想不到用二分。。。
我們首先要通過二分來得到一個x,這個x用于限制區(qū)間中第K大的數(shù)的數(shù)量。什么意思?
我們假設(shè)最后結(jié)果是x,也就是x是最后B中第m大的數(shù)
還有m-1個數(shù)比x大,而在m-1個數(shù)是從A中部分區(qū)間選出的第K大的數(shù),那我們只需要選出這些區(qū)間就足夠了,并不需要全部選出。換句話說,我們?nèi)サ玫降贙大數(shù),此數(shù)大于x的區(qū)間一共有多少個,我們需要m-1個,(因為數(shù)字x是第m個),如果我們得到的區(qū)間不是m-1個,比m-1大,說明你的x取小了,導(dǎo)致更多不符合我們要求的區(qū)間被選進,如果小于m-1,則相反。
這個過程我們可以通過二分+尺取來實現(xiàn)
第k大的數(shù)大于x的區(qū)間的數(shù)量求法:
滿足條件的數(shù)組中,至少應(yīng)該有k個數(shù)大于x,那枚舉區(qū)間左界L時,我們可以直接從L出發(fā)向右掃描看看有多少大于x的數(shù),當大于x的數(shù)正好滿足k個時,將這個位置記為R,在當前位置R再往右掃描,大于x的數(shù)只會比k多不會比k少,也就是R之后的數(shù)與其組成連續(xù)區(qū)間的話都是符合條件的(此處有n-R+1個)。那我們將L向右移動,R也必須向右移動,才能保準k的數(shù)量。
每次二分一個x,都經(jīng)過上述過程
二分+尺取 復(fù)雜度是O(nlogn)
代碼:
如果有點亂,來看看代碼
/* 2 3 1 5 42 3 1 5 2 3 1 5 43 1 5 42 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; } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的牛客网【每日一题】4月22日 K-th Number的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小雨坐地铁
- 下一篇: 牛客网【每日一题】4月24日 子序列