Advertisement
smatskevich

CountingSortOfPoints

Oct 17th, 2016
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. struct CPoint {
  6.     int X;
  7.     int Y;
  8.  
  9.     CPoint( int x, int y ) : X( x ), Y( y ) {}
  10. };
  11.  
  12. // Сортировка точек по X.
  13. void CountingSort( vector<CPoint>& arr, int maxValue )
  14. {
  15.     vector<int> counts( maxValue + 1, 0 );
  16.     // Считаем, сколько раз встретилось каждое число.
  17.     for( int i = 0; i < static_cast<int>( arr.size() ); ++i ) {
  18.         ++counts[static_cast<int>( arr[i].X )];
  19.     }
  20.     // Считаем начало каждой группы. Сохраним их в counts.
  21.     int summ = 0;
  22.     for( int i = 0; i < maxValue + 1; ++i ) {
  23.         int temp = counts[i];
  24.         counts[i] = summ;
  25.         summ += temp;
  26.     }
  27.  
  28.     // Проходим по исходному массиву и заполняем временный массив с результатом. Размера arr.
  29.     vector<CPoint> destination( arr.size(), CPoint( 0, 0 ) );
  30.     for( int i = 0; i < static_cast<int>( arr.size() ); ++i ) {
  31.         destination[counts[arr[i].X]++] = arr[i];
  32.     }
  33.     std::swap( arr, destination ); // O(1).
  34. }
  35.  
  36. int main()
  37. {
  38.     int n = 0;
  39.     cin >> n;
  40.     vector<CPoint> arr( n, CPoint( 0, 0 ) );
  41.     for( int i = 0; i < n; ++i ) {
  42.         cin >> arr[i].X >> arr[i].Y;
  43.     }
  44.  
  45.     CountingSort( arr, 1000000 );
  46.  
  47.     for( int i = 0; i < n; ++i ) {
  48.         cout << arr[i].X << ' ' << arr[i].Y << endl;
  49.     }
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement