Codeforces Round #651 (Div. 2) 參與排名人數14559
[codeforces 1370D] Odd-Even Subsequence 二分查找+跳躍取數
總目錄詳見https://blog.csdn.net/mrcrack/article/details/103564004
在線測評地址https://codeforces.com/contest/1370/problem/D
Problem | Lang | Verdict | Time | Memory |
---|---|---|---|---|
D - Odd-Even Subsequence | GNU C++17 | Accepted | 93 ms | 1000 KB |
題目大意:給定包含n個元素的數組a,選出k個元素,這些元素的前後順序不變,組成數組b,找出在數組b在奇數位置的最大值,找出在數組b在偶數位置的最大值,在這兩個最大值中,找最小值。因選取k個元素,組成數組b,有多種組合,要求在多種組合中,找出最小值,輸出這個最小值。
樣例模擬如下,可結合以下AC代碼進行研究
6 4
5 3 50 2 4 5
3
a數組位置1 2 3 4 5 6
a數組數值5 3 50 2 4 5
只研究cnt=0,x=3這種情況:
從a數組第1個位置開始:cnt++,cnt=1
從a數組第2個位置開始嘗試取值:cnt&1==1,a[2]=3<=3,cnt++,cnt=2,位置2參與取值,此時cnt=2
從a數組第3個位置開始:cnt++,cnt=3
從a數組第4個位置開始:cnt&1==1,a[4]=2<=3,cnt++,cnt=4,位置4參與取值,此時cnt=4
從a數組第5個位置開始:cnt++,cnt=5
從a數組第6個位置開始嘗試取值:cnt&1==1,a[6]=5>3,位置6不參與取值,此時cnt=5
數組a遍歷完畢,但cnt=5>=4,此次遍歷成功,對應數組b的元素是3 50 2 4
b的奇數子序列是{3,2}對應最大值是3
b的偶數子序列是{50,4}對應最大值是50
最大值中取最小值是3
AC代碼如下:
#include <cstdio>
#define maxn 200010
int a[maxn],n,k;
int judge(int x){
int i,cnt;
cnt=0;
for(i=1;i<=n;i++){
if(cnt&1){//從數組a的第2位元素開始嘗試
if(a[i]<=x)cnt++;
}else cnt++;
}
if(cnt>=k)return 1;
cnt=0;
for(i=1;i<=n;i++){
if(!(cnt&1)){//從數組a的第1位元素開始嘗試
if(a[i]<=x)cnt++;
}else cnt++;
}
if(cnt>=k)return 1;
return 0;
}
int main(){
int l,r,i,mid;
scanf("%d%d",&n,&k);
for(i=1;i<=n;i++)scanf("%d",&a[i]);
l=0,r=1000000001;
while(l+1<r){
mid=(l+r)/2;
if(judge(mid))r=mid;
else l=mid;
}
printf("%d\n",r);
return 0;
}