题目链接

自己二分写挂了,得了90分,不知道哪里错了,参考大佬简洁代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <functional>
#include <set>
using namespace std;
typedef pair<int,int> PII;
#define int long long
int s[200010];
int n,h;
signed main()
{
cin>>n>>h;
for(int i=1;i<=n;i++)cin>>s[i],s[i]+=s[i-1];
int m=s[n]-h;
int res=1e9;
for(int i=0;i<n;i++)
{
auto pos=upper_bound(s,s+n+1,s[i]+m);
int t=pos-s;
if(pos!=s+n+1)res=min(res,h-(s[n]-(s[t]-s[i])));
}
if(s[n]<h)cout<<h-s[n]<<'\n';
else cout<<res<<'\n';
}
这篇博客主要讨论了一个使用二分查找算法解决数组中找到最小区间以使得区间和等于给定值的问题。博主分享了自己的实现代码,并参考了一位大神的简洁版本,虽然博主的代码在测试中未能完全通过,但通过对比学习,理解了二分查找在解决此类问题中的关键点。文章最后还考虑了输入数组总和小于给定值的情况,并给出了相应的处理方式。
8461

被折叠的 条评论
为什么被折叠?



