fork download
  1. #include<iostream>
  2. #include<algorithm>
  3. #include<cstring>
  4. #include<string>
  5. #include<cstdio>
  6. #include<vector>
  7. using namespace std;
  8.  
  9. int main()
  10. {
  11. long long n , k, a;
  12. cin >> n >> k;
  13. vector<long long>V;
  14. for ( int i = 0; i < n; i++ )
  15. {
  16. cin >> a;
  17. V.push_back(a);
  18. }
  19.  
  20. sort(V.begin() , V.end());
  21. int count = 0;
  22. int limit = 2;
  23. int j;
  24. long long ans = 0;
  25. for ( int i = n - 1; i >= 0 ; i-- )
  26. {
  27. ans += V [ i ];
  28. ++count;
  29. if ( count == k )
  30. {
  31. j = i;
  32. break;
  33.  
  34. }
  35. }
  36. if(count==k)
  37. {
  38. count = 0;
  39.  
  40. for ( int i = j - 1; i >= 0; i-- )
  41. {
  42. ans += V [ j ];
  43. ++count;
  44. if ( count == k )
  45. {
  46. break;
  47. }
  48. }
  49.  
  50. cout << ans << endl;
  51. }
  52. else
  53. cout << ans << endl;
  54.  
  55. }
Success #stdin #stdout 0s 3436KB
stdin
4 100
10 20 30 40
stdout
100