fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4.  
  5.  
  6. int main(){
  7. int n, q; cin >> n >> q;
  8. int a[n];
  9. for(int i = 0; i < n; i++){
  10. cin >> a[i];
  11. }
  12. // Xây dựng mảng mục tiêu: chỉ số i được truy vấn bao nhiêu lần
  13. // => dùng mảng hiệu
  14. int d[n] = {0};
  15. while(q--){
  16. int l, r; cin >> l >> r;
  17. --l; --r;
  18. d[l] += 1;
  19. d[r + 1] -= 1;
  20. }
  21. // Tính mảng cộng dồn => chính là mảng mục tiêu
  22. int F[n];
  23. F[0] = d[0];
  24. for(int i = 1; i < n; i++){
  25. F[i] = F[i - 1] + d[i];
  26. }
  27. // Sx mảng mục tiêu, mảng ban đầu theo thứ tự giảm dần
  28. sort(F, F + n, greater<int>());
  29. sort(a, a + n, greater<int>());
  30. ll res = 0;
  31. for(int i = 0; i < n; i++){
  32. res += 1ll * a[i] * F[i];
  33. }
  34. cout << res << endl;
  35. }
  36.  
  37.  
Success #stdin #stdout 0.01s 5320KB
stdin
6 2
5 2 5 3 5 1 
2 5
2 4
stdout
33