#651 (Div. 2)D. Odd-Even Subsequence

題目描述

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

input
4 2
1 2 3 4
output
1
input
4 3
1 2 3 4
output
2
input
5 3
5 3 4 2 6
output
2
input
6 4
5 3 50 2 4 5
output
3

Note

In the first test, consider the subsequence s = {1,3}. Here the cost is equal to min(max(1),max(3))=1.
In the second test, consider the subsequence s = {1,2,4}. Here the cost is equal to min(max(1,4),max(2))=2.
In the fourth test, consider the subsequence s = {3,50,2,4}. Here the cost is equal to min(max(3,2),max(50,4))=3.

題目大意

給定包含n個元素的數組a,選出k個元素,這些元素的前後順序不變,組成數組b,找出在數組b在奇數位置的最大值,找出在數組b在偶數位置的最大值,在這兩個最大值中,找最小值。因選取k個元素,組成數組b,有多種組合,要求在多種組合中,找出最小值,輸出這個最小值。

題目分析

因爲答案是取奇區間和偶區間的最小值。所以,當奇區間有最小值時,無論偶區間的答案爲多少都不影響答案。同理,當偶區間有最小值時,無論奇區間的答案爲多少都不影響答案。
因此我們可以枚舉最小值是多少,從而找出符合條件的最小的答案。這個答案存在單調性,因此可以用二分來優化。

因爲不確定這個最小值是屬於奇區間的還是偶區間的,所以可以每次都把兩個區間check一遍。只要有一個符合條件即可。
因爲答案要求的是符合條件的最小值,因此當某次check符合條件時,應當再減小mid(即r=mid-1)看看答案是不是可以更小。

代碼如下
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <map>
#include <unordered_map>
#include <queue>
#include <vector>
#include <set> 
#include <algorithm>
#include <iomanip>
#define LL long long
using namespace std;
const int N=2e5+5;
int n,k,a[N];
bool check(int x,bool flag)
{
	int cnt=0;
	for(int i=1;i<=n;i++)
	if(flag||x>=a[i])
	{
		cnt++;
		flag=!flag;
	}
	return cnt>=k;
}
int main()
{
	cin>>n>>k;
	for(int i=1;i<=n;i++)
	cin>>a[i];
	
	int l=1,r=1e9,ans;
	while(r>=l)
	{
		int mid=l+r>>1;
		if(check(mid,1)||check(mid,0))
		{
			ans=mid;
			r=mid-1;
		}
		else l=mid+1;
	}
	cout<<ans<<endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章