Codeforces Round #479 (Div. 3) C. Less or Equal

C. Less or Equal

题目链接-C. Less or Equal
在这里插入图片描述

在这里插入图片描述
题目大意
一个长度为 n n 的整数序列,你需要求出整数 x x (即 1 x 1 0 9 1≤x≤10^9 ),使得给定序列的 k k 个元素正好小于或等于 x x ,序列可以包含相等的元素,如果没有这样的 x x ,则打印-1

解题思路

  • 将该序列sort排序,判断排序后序列是否可以存在有 k k 个元素正好小于或等于 x x
  • 所以我们需要判断一下是否a[k-1]==a[k],若a[k-1]==a[k],无论如何都不会存在一个x使得序列中恰好有 k k 个元素小于等于 x x
  • 坑点:还需特判一下k==0的情况,k==0时不能直接输出-1k==0说明序列中有零个元素小于等于 x x ,即 x x 需小于序列的最小值
  • 此时需判断一下a[0]是否小于等于 1 1 因为 1 x 1 0 9 1≤x≤10^9 ,所以 x x 不能小于1,若a[0]<=1,说明没有满足条件的 x x ,否则任意输出一个符合条件的 x x ,输出 1 1 即可
  • 具体操作见代码

附上代码

#pragma GCC optimize("-Ofast","-funroll-all-loops")
//#pragma GCC diagnostic error "-std=c++11"
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int dir[4][2]={-1,0,1,0,0,-1,0,1};
const double PI=acos(-1.0);
const double e=exp(1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=2e5+10;
typedef long long ll;
typedef pair<int,int> PII;
typedef unsigned long long ull;
int a[N];
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	int n,k;
	cin>>n>>k;
	for(int i=0;i<n;i++)
		cin>>a[i];
	sort(a,a+n);
	if(!k)
		a[0]<=1?cout<<-1<<endl:cout<<1<<endl;
	else if(a[k-1]==a[k])
		cout<<-1<<endl;
	else 
		cout<<a[k-1]<<endl;
	return 0;
}

发布了175 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Fiveneves/article/details/105424702