fork download
  1. #include <iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. void mergeHelp(vector<pair<int,int> >&store,int start,int mid,int end,vector<int>&ans){
  6. vector<pair<int,int> >temp(end-start+1);
  7.  
  8. int i=start,j=mid,k=0,cnt=0;
  9. while(i<mid && j<=end){
  10. if(store[i].first<=store[j].first){
  11.  
  12. ans[store[i].second]+=cnt;
  13. temp[k++]=store[i++];
  14.  
  15. }else{
  16.  
  17. temp[k++]=store[j++];
  18. cnt++;
  19. }
  20.  
  21. }
  22.  
  23. while(i<mid){
  24. ans[store[i].second]+=cnt;
  25. cout<<"store:"<<store[i].first<<endl;
  26. temp[k++]=store[i++];
  27.  
  28. }
  29.  
  30. while(j<=end){
  31. temp[k++]=store[j++];
  32. }
  33.  
  34. j=start;
  35. for(int i=0;i<k;++i){
  36.  
  37. store[j++]=temp[i];
  38. // cout<<" "<<store[j-1].first<<" ";
  39. }
  40. //cout<<endl;
  41. return;
  42.  
  43. }
  44.  
  45. void countSmaller(vector<pair<int,int> >&store,int start,int end,vector<int>&ans){
  46. if(start<end){
  47. int mid=(start+end)/2;
  48.  
  49. countSmaller(store,start,mid,ans);
  50. countSmaller(store,mid+1,end,ans);
  51.  
  52. mergeHelp(store,start,mid+1,end,ans);
  53. }
  54. return;
  55. }
  56.  
  57. vector<int> countSmaller(vector<int>& nums) {
  58. int size=nums.size();
  59. vector<pair<int,int> >store(size);
  60. for(int i=0;i<size;++i){
  61. store[i]=make_pair(nums[i],i);
  62. }
  63. vector<int>ans(size,0);
  64. countSmaller(store,0,size-1,ans);
  65. return ans;
  66.  
  67. }
  68.  
  69.  
  70. int main() {
  71. vector<int>nums={5, 2, 6, 1};
  72. vector<int>ans=countSmaller(nums);
  73. for(int i=0;i<ans.size();++i){
  74. cout<<ans[i]<<" ";
  75. }
  76. return 0;
  77. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
store:5
store:6
2 1 1 0