fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // Hàm đếm số nghịch thế theo giải pháp O(n^2)
  6. int countInversionsNaive(const vector<int>& arr) {
  7. int n = arr.size();
  8. int count = 0;
  9. for (int i = 0; i < n - 1; i++) {
  10. for (int j = i + 1; j < n; j++) {
  11. if (arr[i] > arr[j]) {
  12. count++;
  13. }
  14. }
  15. }
  16. return count;
  17. }
  18.  
  19. int main() {
  20. int n;
  21. cin >> n;
  22. vector<int> arr(n);
  23. for (int i = 0; i < n; i++) {
  24. cin >> arr[i];
  25. }
  26. cout << "Number of inversions (O(n^2)): " << countInversionsNaive(arr) << endl;
  27. return 0;
  28. }
Success #stdin #stdout 0.01s 5292KB
stdin
6
1 2 4 3 5 1
stdout
Number of inversions (O(n^2)): 5