您的位置:首页 > 其它

Codeforce - 872 - B. Maximum of Maximums of Minimums【思维+贪心】

2017-10-19 21:37 337 查看

B. Maximum of Maximums of Minimums

time limit per test1 second

memory limit per test256 megabytes

inputstandard input

outputstandard output

You are given an array a1, a2, …, an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You’ll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?

Definitions of subsegment and array splitting are given in notes.

Input

The first line contains two integers n and k (1 ≤ k ≤ n ≤  105) — the size of the array a and the number of subsegments you have to split the array to.

The second line contains n integers a1,  a2,  …,  an ( - 109  ≤  ai ≤  109).

Output

Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.

题意 : 给你n个数和一个数k,要求把这n个数分成k份,然后每份的最小值,然后在每份的最小值里选出一个最大值,范围:1 ≤ k ≤ n ≤  105, − 109  ≤  ai ≤  109

分析: 那天做的时候没想出来呀,思路卡死了,后来看了别人的正解发现思路错了,一开始看了还以为是二分,但后来想了想太麻烦了,就没写,正解:首先考虑k值,如果k大于等于3的话,我们就可以把最大值单独分到一个组里面(为什么是3呢,考虑下,因为一串数的话,挑出一串数最多分三段即可),在考虑k = 2时,如果用a数组存的话,很显然 ans = max(a[0],a[n-1]),为什么?要么是第一个,要么是最后一个呢,这样来思考,首先对于第一个元素,只有两种情况,要么它是最小值,要么最小值在右边那一段上,如果是第一种情况的话,在考虑右端点,要么右端点是最小值,要么最小值在左段上,很显然,答案必在这两种情况其中,(当然还有种就是左端点和右端点都是最小值的话,那么最后的答案这两个都可以,所以可以忽略)

参考代码

#include<bits/stdc++.h>
using namespace std;

const int INF = 0x3f3f3f3f;
int main(){
ios_base::sync_with_stdio(0);
int mx = -INF,mn = INF;
int n,k;cin>>n>>k;
int begin,end;  //记录下左右端点
for(int i = 0;i < n;i++){
int x;cin>>x;
if(i == 0) begin = x;
if(i == n-1) end = x;
mx = max(mx,x);
mn = min(mn,x);
}
if(k >= 3) {
cout<<mx<<endl;
}
else if(k == 2) {
cout<<max(begin,end)<<endl;
}
else if(k == 1) {
cout<<mn<<endl;
}
return 0;
}


如有错误或遗漏,请私聊下UP,thx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: