标签:
思路:先把序列排序,然后对于某个最佳答案,肯定有一个位置值是不用变的,那么只要能高效维护每个位置的答案即可,这个只需要从左往右和从右往左各扫一遍,记录下左边和右边答案即可,第二遍扫的时候更新一下最大值即可
代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long ll; const int N = 100005; int n; ll a[N], l[N], r[N]; int main() { while (~scanf("%d", &n)) { ll ans = 1000000000000000LL; for (int i = 1; i <= n; i++) scanf("%lld", &a[i]); sort(a + 1, a + n + 1); a[n + 1] = a[n] + 1; for (int i = 1; i <= n; i++) { l[i] = l[i - 1] + (a[i] - a[i - 1] - 1) * (i - 1); } for (int i = n; i >= 1; i--) { r[i] = r[i + 1] + (a[i + 1] - a[i] - 1) * (n - i); ans = min(l[i] + r[i], ans); } printf("%lld\n", ans); } return 0; }
标签:
原文地址:http://blog.csdn.net/accelerator_/article/details/42239079