Educational Codeforces Round 114 (Rated for Div. 2)-C. Slay the Dragon

原题链接:Educational Codeforces Round 114 (Rated for Div. 2)-C. Slay the Dragon
算法:二分
思路:明显由于题中数据范围太大,我们一定要考虑优化时间复杂度,由二段性用二分,数据太大也要防止爆数据用long long读入的时候cin太慢用scanf快
具体看代码实现

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5+5;
LL c[N];

int bsearch_1(int l,int r,LL x)
{
	while (l<r)
	{
		int mid=l+1ll+r>>1;
		if (c[mid]<=x) l=mid;
		else r=mid-1;
	}
	return l;
}

int bsearch_2(int l,int r,LL x)
{
	while (l<r)
	{
		int mid=l+r>>1;
		if (c[mid]>=x) r=mid;
		else l=mid+1;
	}
	return l;
}
int main()
{
	int n; cin>>n;
	LL sum=0;
	for (int i=1;i<=n;i++) scanf("%lld",&c[i]),sum+=c[i];
	sort(c+1,c+n+1);
	int m; scanf("%d",&m);
	while (m--)
	{
		LL a,b; scanf("%lld%lld",&a,&b);
		int l=bsearch_2(1,n,a);
		int r=bsearch_1(1,n,a);
		LL ans=0;
		if (c[l]==a||c[r]==a) ans=b-sum+c[l]<0?0:b-sum+c[l];
		else
		{
			LL ans1=(c[l]-a>0?0:fabs(c[l]-a))+(b-sum+c[l]<0?0:b-sum+c[l]);
			LL ans2=(c[r]-a<0?fabs(c[r]-a):0)+(b-sum+c[r]<0?0:b-sum+c[r]);
			ans=min(ans1,ans2);
		}
		printf("%lld\n",ans);
	}
	return 0;
}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值