大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.4 KiB

  1. #include<iostream>
  2. #include<vector>
  3. using namespace std;
  4. const int N=200000;
  5. void merge__(vector<int>& arr, vector<int>& tmp, int l, int mid, int r, int& ret) {
  6. int i = l, j = mid + 1, k = 0;
  7. while (i <= mid && j <= r) {
  8. if (arr[i] > arr[j]) {
  9. tmp[k++] = arr[j++];
  10. ret += (mid - i + 1);
  11. }
  12. else {
  13. tmp[k++] = arr[i++];
  14. }
  15. }
  16. while (i <= mid) {
  17. tmp[k++] = arr[i++];
  18. }
  19. while (j <= r) {
  20. tmp[k++] = arr[j++];
  21. }
  22. for (k = 0, i = l; i <= r; ++i, ++k) {
  23. arr[i] = tmp[k];
  24. }
  25. }
  26. void merge_sort__(vector<int>& arr, vector<int>& tmp, int l, int r, int& ret) {
  27. if (l >= r) {
  28. return;
  29. }
  30. int mid = l + ((r - l) >> 1);
  31. merge_sort__(arr, tmp, l, mid, ret);
  32. merge_sort__(arr, tmp, mid + 1, r, ret);
  33. merge__(arr, tmp, l, mid, r, ret);
  34. }
  35. int InversePairs(vector<int>& nums) {
  36. // write code here
  37. int ret = 0;
  38. // 在最外层开辟数组
  39. vector<int> tmp(nums.size());
  40. merge_sort__(nums, tmp, 0, nums.size() - 1, ret);
  41. return ret;
  42. }
  43. int main()
  44. {
  45. vector<int> q;
  46. int n,a;
  47. cin >> n;
  48. int result;
  49. for(int i=0;i<n;i++){
  50. cin >>a;
  51. q.push_back(a);
  52. }
  53. for(int i=0;i<n;i++){
  54. q[i] = -q[i];
  55. result = InversePairs(q);
  56. cout << result<< ' ';
  57. q[i] = -q[i];
  58. }
  59. return 0;
  60. }