一:排序不等式

这个题需要注意数据的范围,粗略的计算数据范围是50亿,int的数据范围是20亿,所以结果需要使用long long
image.png

  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4. const int N = 1e5 + 10;
  5. typedef long long LL;
  6. int n, a[N];
  7. int main()
  8. {
  9. ios::sync_with_stdio(false);
  10. cin >> n;
  11. for (int i = 1; i <= n; i++)
  12. cin >> a[i];
  13. sort(a + 1 , a + n + 1); // 使用注意,默认从小到大排序
  14. LL res = 0;
  15. for (int i = 1; i <= n; i++)
  16. res += a[i] * (n - i);
  17. cout << res << endl;
  18. return 0;
  19. }

二:绝对值不等式

image.png
下面分析a-x和b-x的绝对值的时候,发现当x在a和b的中间的时候,距离就是b-a,无论在a,b区间的左边还是右边,这个值都会多出两倍的距离来,下图的y总两两组合就是应用的a-x和b-x的原理,所以我们推测我们要选择的就是中间位置的点,注意这个题选择的时候数轴上已经存在的点,偶数个点随便选择中间两个点某个点就可以,如果是奇数个点的时候,直接选择即可。
image.png

  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4. const int N = 1e5 +10;
  5. int a[N];
  6. int n;
  7. int main()
  8. {
  9. ios::sync_with_stdio(false);
  10. cin >> n;
  11. for (int i = 0; i < n; i++)
  12. cin >> a[i];
  13. sort(a, a + n);
  14. int res = 0;
  15. for (int i = 0; i < n; i++)
  16. {
  17. res += abs(a[i] - a[n / 2]);
  18. }
  19. cout << res << endl;
  20. return 0;
  21. }

三:不等式