当前位置: 首页 > 工具软件 > Dragon Player > 使用案例 >

slay the dragon

东方和煦
2023-12-01

参考了一下tourist的代码
C. Slay the Dragon
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n;
	cin >> n;
	vector<long long> a(n);
	long long sum=0;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
		sum += a[i];
	}
	sort(a.begin(), a.end());
	int m;
	cin >> m;
	while (m--) {
		long long x, y;
		cin >> x >> y;`在这里插入代码片`
		long long ans = 9e18;
		auto it = lower_bound(a.begin(), a.end(),x);
		if (it != a.end()) {
			long long remain = sum - *(it);
			long long add = max(0ll, y-remain);
			ans = min(ans, add);
		}
		if (it != a.begin()) {
			long long remain = sum - *prev(it);
			long long add = max(0ll, x - *prev(it));
			add += max(0ll, y - remain);
			ans = min(ans, add);
		}
		cout << ans << endl;
	}
	return 0;
}

只要二分找到第一个小于x的值和第一个大于x的值,分别算一算花费,哪个小就去哪个。
说实话大神的代码真的简洁,不像我的又臭又长。

 类似资料:

相关阅读

相关文章

相关问答