#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;
}

猜你喜欢

转载自blog.csdn.net/li_wen_zhuo/article/details/106896308