Odd-Even Subsequence codeforces 1370D

D. Odd-Even Subsequence
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Ashish has an array a of size n.

A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.

Consider a subsequence s of a. He defines the cost of s as the minimum between:

The maximum among all elements at odd indices of s.
The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s1,s3,s5,…),max(s2,s4,s6,…)).

For example, the cost of {7,5,6} is min(max(7,6),max(5))=min(7,5)=5.

Help him find the minimum cost of a subsequence of size k.

Input
The first line contains two integers n and k (2≤k≤n≤2⋅105) — the size of the array a and the size of the subsequence.

The next line contains n integers a1,a2,…,an (1≤ai≤109) — the elements of the array a.

Output
Output a single integer — the minimum cost of a subsequence of size k.

Examples
inputCopy
4 2
1 2 3 4
outputCopy
1
二分的判斷條件是這樣,先以偶數個爲準,選比mid小的數,記錄選出的數的個數,這樣就可以確保最終結果小於等於mid,這樣所選出的數的個數是最多的,然後與k進行比較進而選擇二分的區間,奇數個爲準的時候一樣。

#include <iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
int a[200005];
int n,k;
int checking(int mid)
{
    int cnt=0;
    for(int i=1;i<=n;i++)
    {
        if(cnt%2==1)
        {
            cnt++;
        }
        else if(a[i]<=mid) cnt++;
    }
    if(cnt>=k) return 1;
    cnt=0;
    for(int i=1;i<=n;i++)
    {
        if(cnt%2==0)
        {
            cnt++;
        }
        else if(a[i]<=mid)
        {
            cnt++;
        }
    }
    if(cnt>=k) return 1;
    return 0;
}
int main()
{
    scanf("%d%d",&n,&k);
    int l=0,r=1e9;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    int mid;
    int ans;
    while(l<=r)
    {
        mid=(l+r)/2;
        if(checking(mid))
        {
            r=mid-1;
            ans=mid;
        }
        else
            l=mid+1;
    }
    printf("%d\n",ans);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章