Advertisement
Spocoman

01. Merge Trains

Oct 31st, 2023 (edited)
559
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <list>
  5.  
  6. using namespace std;
  7.  
  8. list<int> split(string str) {
  9.     getline(cin, str);
  10.     istringstream s(str);
  11.     list<int> numbers;
  12.     int n;
  13.  
  14.     while (s >> n) {
  15.         numbers.push_back(n);
  16.     }
  17.  
  18.     return numbers;
  19. }
  20.  
  21. int main() {
  22.     string line, wagon, listMergeVagons;
  23.    
  24.     list<int> trackA = split(line);
  25.     list<int> trackB = split(line);
  26.     list<int> vagonsMerge;
  27.  
  28.     while (trackA.size() + trackB.size() != 0) {
  29.         wagon = trackA.empty() ? "B" :
  30.                 trackB.empty() ? "A" :
  31.                 (trackA.back() < trackB.back() ? "A" : "B");
  32.        
  33.         vagonsMerge.push_front(wagon == "A" ? trackA.back() : trackB.back());
  34.         wagon == "A" ? trackA.pop_back() : trackB.pop_back();
  35.         listMergeVagons += wagon;
  36.     }
  37.  
  38.     cout << listMergeVagons << endl;
  39.  
  40.     for (auto& w : vagonsMerge) {
  41.         cout << w << ' ';
  42.     }
  43.  
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement