Educational Codeforces Round 114 (Rated for Div. 2) 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 11 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≤𝑛≤2⋅1052≤n≤2⋅105) — number of heroes.
The second line contains 𝑛n integers 𝑎1,𝑎2,…,𝑎𝑛a1,a2,…,an (1≤𝑎𝑖≤10121≤ai≤1012), where 𝑎𝑖ai is the strength of the 𝑖i-th hero.
The third line contains a single integer 𝑚m (1≤𝑚≤2⋅1051≤m≤2⋅105) — the number of dragons.
The next 𝑚m lines contain two integers each, 𝑥𝑖xi and 𝑦𝑖yi (1≤𝑥𝑖≤1012;1≤𝑦𝑖≤10181≤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.
Example
input
Copy
4
3 6 2 3
5
3 12
7 9
4 14
1 10
8 7
output
Copy
1
2
4
0
2
贪心的思想。首先对a数组排序,然后在数组中二分找到距离defense最近的(左右两边)两个a1、a2,最终要增加的就是这两者之一。找到更优的那个即可。证明的话分类讨论一下defense、attack、a和sum - a的关系大概就能看出来了。下面的代码必须关同步流才能过。
#include <bits/stdc++.h>
using namespace std;
int n, m;
long long a[200005];
long long sum = 0;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> a[i];
sum += a[i];
}
cin >> m;
sort(a + 1, a + n + 1);
for(int i = 1; i <= m; i++) {
long long x, y;
cin >> x >> y;
int pos1 = lower_bound(a + 1, a + n + 1, x) - a;
int pos2 = lower_bound(a + 1, a + n + 1, x) - a - 1;
long long ans = 2e18;//不能是1e18!!!因为y的最大值就是1e18
if(a[pos1] >= x) {
ans = min(ans, max(y - (sum - a[pos1]), 0ll));
}
if(a[pos2] < x && pos2 <= n && pos2 >= 1) {
ans = min(ans, (x - a[pos2]) + max(y - (sum - a[pos2]), 0ll));
}
cout << ans << endl;
}
return 0;
}