More Cowbell CodeForces - 604B (二分+贪心)

水题,贪心+二分

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn=1e6+5;
typedef long long ll;
ll n,k,a[maxn];
bool check(ll mid) {
	int l=1,r=n,cnt=0;
	while(l<=r){
		if(a[r]>mid) return false;
		if(l!=r) {
			if(a[l]+a[r]<=mid)l++,r--;
			else r--;
		} else l++;
		cnt++;
	}
	if(cnt<=k)return true;
	return false;
}
int main() {
	cin>>n>>k;
	for(int i=1; i<=n; i++)cin>>a[i];
	ll l=1,r=1e18;
	while(l<r) {
		ll mid=l+(r-l)/2;
		if(check(mid))r=mid;
		else l=mid+1;
	}
	cout<<l<<endl;
}

猜你喜欢

转载自blog.csdn.net/Alanrookie/article/details/106912737