Advertisement
Guest User

Untitled

a guest
Jan 24th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.32 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. class HashTable
  7. {
  8. public:
  9.     size_t table_size = 2 * 256;
  10.  
  11. public:
  12.     HashTable(int sz)                   // создает и инициализирует таблицу.
  13.     {
  14.         hash_table.resize(sz);
  15.         table_size = sz;
  16.         for(size_t i = 0; i < table_size; ++i) {
  17.             hash_table[i].second = 0;
  18.         }
  19.     }
  20.  
  21.     size_t hash(string a) {             // хэширует строку
  22.         if (a.size() == 1) {
  23.             return int(a[0]);
  24.         }
  25.         return int(a[0] + a[1]);
  26.     }
  27.  
  28.     bool add(string a) {                            // добавляет строку в хэш таблицу. Возвращает 1 если получилось добавить, 0 если нет.
  29.         int pos = hash(a);
  30.         while(pos < table_size && hash_table[pos].second) pos++;
  31.         if (pos == table_size)
  32.             return 0;
  33.         hash_table[pos].first = a;
  34.         hash_table[pos].second = 1;
  35.         return 1;
  36.     }
  37.  
  38.     pair <string, bool> get(size_t pos) {
  39.         return hash_table[pos];
  40.     }
  41.  
  42. private:
  43.     vector <pair<string, bool>> hash_table;
  44. };
  45.  
  46. int main()
  47. {
  48.     int cnt = 0;
  49.     vector <string> strings;
  50.     string s;
  51.     freopen("/users/staff/staroverov/lectures/images/t0.txt", "r", stdin);
  52.     // считываем строки и заносим в массив
  53.     while (cin >> s) {
  54.         cnt++;
  55.         strings.push_back(s);
  56.     }
  57.     // создаем хэш-таблицу и добавляем туда строки
  58.     HashTable ht(cnt * 2);
  59.     cout << ht.table_size;
  60.     for (size_t i = 0; i < cnt; ++i) {
  61.         ht.add(strings[i]);
  62.     }
  63.     // выводим в файлы строки
  64.     for (size_t i = 0; i < cnt * 2; ++i) {
  65.         pair <string, bool> tmp = ht.get(i);
  66.         if (!tmp.second) continue ;
  67.         ofstream out;
  68.         string num = "";
  69.         int c = i;
  70.         if (!c) {
  71.             num += '0';
  72.         } else {
  73.             while (c) {
  74.                 num += '0' + (c % 10);
  75.                 c /= 10;
  76.             }
  77.         }
  78.         reverse(num.begin(), num.end());
  79.         num += ".txt";
  80.         out.open(num);
  81.         if (out.is_open()) {
  82.             out << tmp.first << endl;
  83.             out.close();
  84.         }
  85.     }
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement