#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int n;
int t[N];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &t[i]);
sort(t, t + n);
long long res = 0;
for (int i = 0; i < n; i++) res += t[i] * (n - 1 - i);
printf("%lld\n", res);
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int n;
int q[N];
int main()
{
cin >> n;
for (int i = 0; i < n; i++) cin >> q[i];
sort(q, q + n);
int res = 0;
for (int i = 0; i < n; i++) res += abs(q[i] - q[n / 2]);
cout << res << endl;
return 0;
}
耍杂技的牛
与国王游戏的贪心策略相似, 我们先分析每头牛的危险值 = 他前面牛的w(重量值)和 - 自身的s(强壮值),要使每头牛的危险值最小,这显然是与w 和 s同时相关。按每头牛的 w + s 进行排序, 当存在逆序时就进行交换(即升序排序),然后根据题意算出每头牛的危险值记录其中的最大值即可。
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 50010;
int n;
PII cow[N];
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ )
{
int s, w;
cin >> w >> s;
cow[i] = {w + s, w};
}
sort(cow, cow + n);
int res = -2e9, sum = 0;
for (int i = 0; i < n; i ++ )
{
int s = cow[i].first - cow[i].second, w = cow[i].second;
res = max(res, sum - s);
sum += w;
}
cout << res << endl;
return 0;
}