fork(1) download
  1. #include <iostream>
  2. #include <map>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. int main() {
  8. vector<int> A; //here we have our input array
  9. int n; //number of elements
  10. //read input
  11. scanf("%d",&n);
  12. A.resize(n);
  13. for(int i=0; i<n; i++) scanf("%d",&A[i]);
  14.  
  15. //create second array with positions
  16. vector<pair<int,int> > B;
  17. for(int i=0; i<n; i++) B.push_back(make_pair(A[i],i));
  18. sort(B.begin(),B.end());
  19. map<int,int> M; //here is mapping from numbers 1 to n to real numbers in A
  20. //let's replace array A with new smaller elements
  21. for(int i=0; i<n; i++) {
  22. if(M.find(B[i].first)==M.end()) M[B[i].first]=M.size();
  23. A[B[i].second]=M[B[i].first];
  24. }
  25.  
  26. //now in array A we have elements between 1 to n
  27. //and in map M we hold original number for every new number
  28.  
  29. //result array
  30. for(int i=0; i<n; i++) printf("%d ",A[i]); printf("\n");
  31. //result mapping
  32. for(map<int,int>::iterator it=M.begin(); it!=M.end(); it++)
  33. printf("%d: %d\n",(*it).second,(*it).first);
  34. return 0;
  35. }
Success #stdin #stdout 0s 2824KB
stdin
6
-4 8 4 4 1 -20
stdout
2 5 4 4 3 1 
1: -20
2: -4
3: 1
4: 4
5: 8