Guest User

7. Hot Potato

a guest
May 31st, 2021
73
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <list>
  3. #include <string>
  4. #include <sstream>
  5.  
  6. std::list<std::string> readInput(std::string &turns) {
  7.     std::list<std::string> names;
  8.     std::string line;
  9.     getline(std::cin, line);
  10.     std::istringstream istr(line);
  11.     std::string name;
  12.     while (istr >> name) {
  13.         names.push_back(name);
  14.     }
  15.     getline(std::cin, turns);
  16.     return names;
  17. }
  18.  
  19. std::string hotPotato(const int turns, std::list<std::string>& names) {
  20.     int currTurns = turns;
  21.     std::list<std::string>::iterator it = names.begin();
  22.     currTurns--; //by pointing the first is one turn
  23.     while (names.size() != 1) {
  24.         if (currTurns == 0) {
  25.             currTurns = turns;
  26.             currTurns--;
  27.             std::cout << "Removed " << *it << std::endl;
  28.             it = names.erase(it);
  29.             if (it == names.end()) {
  30.                 it = names.begin();
  31.             }
  32.             continue;
  33.         }
  34.         ++it;
  35.         if (it == names.end()) {
  36.             it = names.begin();
  37.         }
  38.         currTurns--;
  39.     }
  40.     return *it;
  41. }
  42.  
  43. int main()
  44. {
  45.     std::string turnsStr;
  46.     std::list<std::string> names = readInput(turnsStr);
  47.     int turns = stoi(turnsStr);
  48.     std::cout << "Last is " << hotPotato(turns, names);
  49. }
  50.  
  51.  
  52.  
RAW Paste Data