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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值