fork download
  1. #include <iostream>
  2. #include <chrono>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6. using namespace std::chrono;
  7. constexpr size_t size = 10000000;
  8.  
  9. void fill_array (int T[size]) {
  10. for (size_t counter = 0, i = 0; counter < size / 2; ++i) {
  11. if (i == size - 1)
  12. i = 0;
  13.  
  14. if (rand() % 3 == 0 && T[i] == 0) {
  15. T[i] = rand();
  16. ++counter;
  17. }
  18. }
  19. }
  20.  
  21. size_t solution (int T[size]) {
  22. size_t sum = 0;
  23.  
  24. for (size_t i = 0; i < size; ++i) {
  25. if (T[i] != 0) {
  26. sum += T[i];
  27. }
  28. }
  29.  
  30. return sum;
  31. }
  32.  
  33.  
  34. int main () {
  35. int *Array = new int[size];
  36. fill_array(Array);
  37.  
  38. {
  39. high_resolution_clock::time_point start = high_resolution_clock::now();
  40. cout << solution(Array) << endl;
  41. high_resolution_clock::time_point stop = high_resolution_clock::now();
  42.  
  43. auto time_span = duration_cast<chrono::microseconds>(stop - start);
  44.  
  45. std::cout << "without sorting: " << time_span.count() << " microseconds" << endl;
  46. }
  47.  
  48. // ----------------------------------------------------------------------
  49.  
  50. sort(Array, Array + size);
  51. {
  52. high_resolution_clock::time_point start = high_resolution_clock::now();
  53. cout << solution(Array) << endl;
  54. high_resolution_clock::time_point stop = high_resolution_clock::now();
  55.  
  56. auto time_span = duration_cast<chrono::microseconds>(stop - start);
  57.  
  58. std::cout << "after sorting: " << time_span.count() << " microseconds" << endl;
  59. }
  60.  
  61. delete[] Array;
  62. return 0;
  63. }
Success #stdin #stdout 1.68s 3416KB
stdin
Standard input is empty
stdout
2351769765
without sorting: 50731 microseconds
2351769765
after sorting: 20426 microseconds