Vic22

X39285 - Merge of inverted vectors

Jan 14th, 2020
76
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5.  
  6. //reads  vector u from cin
  7. void read_vector(vector<int>& u) {
  8.     int n = u.size();
  9.     for (int i = 0; i < n; ++i) cin >> u[i];
  10. }
  11.  
  12. //u is a non-empty vector
  13. //writes vector u on cout
  14. void write_vector(const vector<int>& u) {
  15.     int n = u.size();
  16.     cout << u[0];
  17.     for (int i = 1; i < n; ++i) cout << ' ' << u[i];
  18.     cout << endl;
  19. }
  20.  
  21. //u is in increasing order, v is in decreasing order
  22. //returns a vector w  with both u and v values in increasing order  
  23. vector<int> i_merge(const vector<int>& u, const vector<int>&v){
  24.     int n = u.size();
  25.     int m = v.size();
  26.     vector<int> w(n + m);
  27.     int i = 0;
  28.     int j = m-1;
  29.     for (int k = 0; k < n+m; ++k){
  30.         if (i < n and j >= 0){
  31.             if (u[i] <= v[j]) {
  32.                 w[k] = u[i];
  33.                 ++i;
  34.             }
  35.             else {
  36.                 w[k] = v[j];
  37.                 --j;
  38.             }
  39.         }
  40.         else if (i == n and j >= 0){
  41.             w[k] = v[j];
  42.             --j;
  43.         }
  44.         else if (i < n and j < 0){
  45.             w[k] = u[i];
  46.             ++i;
  47.         }
  48.     }
  49.     return w;
  50. }
  51.  
  52. int main() {
  53.     int n;
  54.     cin >> n;
  55.     vector<int> u(n);
  56.     read_vector(u);
  57.     int m;
  58.     cin >> m;
  59.     vector<int> v(m);
  60.     read_vector(v);
  61.     vector <int> w = i_merge(u, v);
  62.     write_vector(w);
  63. }
RAW Paste Data