题解 | #游游的元素修改#
游游的元素修改
https://www.nowcoder.com/practice/2e3557c96138444db7eca60e8afaaac7
维护一个总和 sum ,如果 sum/n 向下取整大于等于 l 且 sum/n 向上取整小于等于 r ,那么代表一定有解,此时就看超出 l 和 r 的部分谁大了,答案就是大的那个,反之无解
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 2e5 + 5; int __t = 1, n, l, r, a; void solve() { cin >> n >> l >> r; int sum = 0, p = 0, d = 0; for (int i = 0; i < n; i++) { cin >> a; sum += a; if (a < l) p += l - a; if (a > r) d += a - r; } if (sum / n >= l && (sum + n - 1) / n <= r) { cout << max(p, d) << "\n"; return; } cout << "-1\n"; return; } int32_t main() { #ifdef ONLINE_JUDGE ios::sync_with_stdio(false); cin.tie(0); #endif cin >> __t; while (__t--) solve(); return 0; }