Advertisement
thinhhja2001

Untitled

Apr 4th, 2020
679
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. // 1 số mẫu test: => random 1 mảng 1 chiều có số lượng phần tử từ ít tới nhiều
  2. // 10 phần tử, 100 phần tử, 1,000, 10,000, 100,000 phần tử
  3.  
  4. #include <iostream>
  5. #include <stdlib.h>     /* srand, rand */
  6. #include <time.h>
  7. using namespace std;
  8. double ThuatToan1(int a[], int n,double time_use) {
  9.     int maxSum = 0;
  10.     clock_t start, end;
  11.     for (int i = 0; i < n; i++)
  12.     {
  13.         start = clock();
  14.         for (int j = i; j < n; j++)
  15.         {
  16.             int thisSum = 0;
  17.             for (int k = i; k <= j; k++)
  18.                 thisSum += a[k];
  19.             if (thisSum > maxSum)
  20.                 maxSum = thisSum;
  21.         }      
  22.         end = clock();
  23.         double time = (double)(end - start) / CLOCKS_PER_SEC;
  24.         time_use += time;
  25.         if (time_use > 30)
  26.             return -1;
  27.     }
  28.  
  29.     cout << maxSum << endl;
  30.     return time_use;
  31. }
  32.  
  33. double ThuatToan2(int a[],int n,double time_use)
  34. {
  35.     int maxSum = 0, thisSum = 0;
  36.     clock_t start, end;  
  37.    
  38.     for (int j = 0; j < n; j++)
  39.     {
  40.         start = clock();
  41.         thisSum += a[j];
  42.         if (thisSum > maxSum)
  43.             maxSum = thisSum;
  44.         else if (thisSum < 0)
  45.             thisSum = 0;
  46.         end = clock();
  47.         double time = (double)(end - start) / CLOCKS_PER_SEC;
  48.         time_use += time;
  49.         if (time_use > 30)
  50.             return -1;
  51.     }
  52.  
  53.     cout << maxSum << endl;
  54.     return time_use;
  55. }
  56.  
  57. void RandomArray(int a[], int n) {
  58.     srand(time(NULL));
  59.     for (int i = 0;i<n;i++)
  60.         a[i] = rand() % 100000;
  61.  
  62. }
  63. int main()
  64. {
  65.     double time_use = 0;
  66.     int n;
  67.     cout << "nhap so luong phan tu ban muon \n";
  68.     cin >> n;
  69.     int a[100000];
  70.     RandomArray(a, n);
  71.     cout << "Thoi gian thuc hien thuat toan 1 la:\n";
  72.     if (ThuatToan1(a, n, time_use) == -1)
  73.     {
  74.         cout << "Qua 30s\n";
  75.     }
  76.     else
  77.         cout << ThuatToan1(a, n, time_use) << "giay\n";
  78.     cout << "Thoi gian thuc hien thuat toan 2 la:\n";
  79.     if (ThuatToan2(a, n, time_use) == -1)
  80.     {
  81.         cout << "Qua 30s\n";
  82.     }
  83.     else
  84.         cout << ThuatToan2(a, n, time_use) << "giay\n";
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement