Advertisement
Spocoman

02. Santa's Gifts

Feb 11th, 2024 (edited)
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. vector<string> split(string& str) {
  9.     vector<string> v;
  10.     istringstream ss(str);
  11.     string s;
  12.     while (ss >> s) {
  13.         v.push_back(s);
  14.     }
  15.     return v;
  16. }
  17.  
  18. int getIndex(vector<string>& v, string s) {
  19.     for (int i = 0; i < v.size(); i++) {
  20.         if (v[i] == s) {
  21.             return i;
  22.         }
  23.     }
  24.     return -1;
  25. }
  26.  
  27. int main() {
  28.     int commandNumbers, index = 0;
  29.     cin >> commandNumbers;
  30.     cin.ignore();
  31.  
  32.     string line;
  33.     getline(cin, line);
  34.  
  35.     vector<string> command, houses = split(line);
  36.  
  37.     for (int i = 0; i < commandNumbers; i++) {
  38.         int currentIndex = index;
  39.  
  40.         getline(cin, line);
  41.         command = split(line);
  42.  
  43.         if (command[0] == "Forward" || command[0] == "Back") {
  44.             int steps = stoi(command[1]);
  45.             currentIndex += (command[0] == "Forward" ? steps : -steps);
  46.             if (currentIndex >= 0 && currentIndex < houses.size()) {
  47.                 index = currentIndex;
  48.                 houses.erase(houses.begin() + index);
  49.             }
  50.         }
  51.         else if (command[0] == "Gift") {
  52.             currentIndex = stoi(command[1]);
  53.             if (currentIndex >= 0 && currentIndex < houses.size()) {
  54.                 index = currentIndex;
  55.                 houses.insert(houses.begin() + index, command[2]);
  56.             }
  57.         }
  58.         else {
  59.             int index1 = getIndex(houses, command[1]),
  60.                 index2 = getIndex(houses, command[2]);
  61.  
  62.             if (index1 != -1 && index2 != -1) {
  63.                 string value = houses[index1];
  64.                 houses[index1] = houses[index2];
  65.                 houses[index2] = value;
  66.             }
  67.         }
  68.     }
  69.  
  70.     cout << "Position: " << index << endl;
  71.  
  72.     if (!houses.empty()) {
  73.         for (int i = 0; i < houses.size(); i++) {
  74.             cout << houses[i] << (i != houses.size() - 1 ? ", " : "");
  75.         }
  76.     }
  77.  
  78.     cout << endl;
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement