C. Slay the Dragon

Recently, Petya learned about a new game “Slay the Dragon”. As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of n heroes, the strength of the i-th hero is equal to ai.

According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon’s defense is equal to x, then you have to send a hero with a strength of at least x to kill it. If the dragon’s attack power is y, then the total strength of the heroes defending the castle should be at least y.
The player can increase the strength of any hero by 1 for one gold coin. This operation can be done any number of times.
There are m dragons in the game, the i-th of them has defense equal to xi and attack power equal to yi. Petya was wondering what is the minimum number of coins he needs to spend to defeat the i-th dragon.
Note that the task is solved independently for each dragon (improvements are not saved).
Input
The first line contains a single integer n (2≤n≤2⋅105) — number of heroes.
The second line contains n integers a1,a2,…,an (1≤ai≤1012), where ai is the strength of the i-th hero.
The third line contains a single integer m (1≤m≤2⋅105) — the number of dragons.
The next m lines contain two integers each, xi and yi (1≤xi≤1012;1≤yi≤1018) — defense and attack power of the i-th dragon.
Output
Print m lines, i-th of which contains a single integer — the minimum number of coins that should be spent to defeat the i-th dragon.

input

4
3 6 2 3
5
3 12
7 9
4 14
1 10
8 7

output

1
2
4
0
2

先二分查找判断能不能找到,若能找到则使用这个值。
找不到就判断比所有制都大还是比所有值都小,还是在这个值的区间范围内。
若是比所有值都大则使用最大值
比所有值都小使用最小值。
若在这两个值范围之内则分别使用查找出的i和i-1求出结果取min

#include<stdio.h>
#include<
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Prime me

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值