fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9. int t;
  10. cin >> t; // Number of test cases
  11.  
  12. while (t--) {
  13. int n, k;
  14. cin >> n >> k; // Input size of array and number of initial blue elements
  15. vector<int> a(n);
  16.  
  17. for (int i = 0; i < n; i++) {
  18. cin >> a[i];
  19. }
  20.  
  21. // Sort the array in descending order
  22. sort(a.begin(), a.end(), greater<int>());
  23.  
  24. // First k elements selected as blue
  25. long long cost = 0;
  26. for (int i = 0; i < k; i++) {
  27. cost += a[i];
  28. }
  29.  
  30. // Remaining red elements
  31. priority_queue<int> red_elements;
  32. for (int i = k; i < n; i++) {
  33. red_elements.push(a[i]);
  34. }
  35.  
  36. // Simulating the spreading process
  37. while (!red_elements.empty()) {
  38. int current = red_elements.top();
  39. red_elements.pop();
  40. // Add the largest remaining red element to the cost
  41. cost += current;
  42. break; // Once the largest red element is added, stop
  43. }
  44.  
  45. cout << cost << endl;
  46. }
  47.  
  48. return 0;
  49. }
  50.  
Success #stdin #stdout 0.01s 5288KB
stdin
3
3 1
1 2 3
5 2
4 2 3 1 3
4 3
2 2 2 2
stdout
5
10
8