Advertisement
Guest User

Untitled

a guest
Jan 10th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <unordered_set>
  3. #include <unordered_map>
  4. #include <map>
  5.  
  6. class Database {
  7. private:
  8.   std::unordered_set<std::string> ids;
  9.   std::unordered_map<std::string, size_t> nameCount; // name -> count of users with the name
  10.   std::map<size_t, size_t> ageCount; // age -> count of users of that age
  11. public:
  12.   void add(std::string id, const std::string& name, size_t age) {
  13.     if (this->ids.find(id) != this->ids.end()) {
  14.       return;
  15.     }
  16.  
  17.     this->ids.emplace(id);
  18.     ++this->nameCount[name];
  19.     ++this->ageCount[age];
  20.   }
  21.  
  22.   size_t countByName(const std::string& name) const {
  23.     auto const& pair = this->nameCount.find(name);
  24.     return (pair == this->nameCount.end()) ? 0 : pair->second;
  25.   }
  26.  
  27.   size_t countByAgeRange(size_t startAge, size_t endAge) const {
  28.     size_t count = 0;
  29.     auto const& end = this->ageCount.lower_bound(endAge);
  30.     for (auto it = this->ageCount.lower_bound(startAge); it != end; ++it) {
  31.       count += it->second;
  32.     }
  33.     return count;
  34.   }
  35. };
  36.  
  37. int main() {
  38.   std::ios_base::sync_with_stdio(false);
  39.   std::cin.tie(nullptr);
  40.  
  41.   Database db;
  42.  
  43.   std::string command, id, name;
  44.   size_t age, ageStart, ageEnd;
  45.  
  46.   while ((std::cin >> command) && command != "end") {
  47.     if (command == "entry") {
  48.       std::cin >> id >> name >> age;
  49.       db.add(id, name, age);
  50.     } else if (command == "name") {
  51.       std::cin >> name;
  52.       std::cout << db.countByName(name) << std::endl;
  53.     } else if (command == "age") {
  54.       std::cin >> ageStart >> ageEnd;
  55.       std::cout << db.countByAgeRange(ageStart, ageEnd) << std::endl;
  56.     }
  57.   }
  58.  
  59.   return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement