Рабочий стол > DL Руководство пользователя > ... > Полезные факты о С++ и примеры задач > lower_bound > Information > Сравнить страницу
lower_bound Войти | Зарегистрироваться   Просмотр версии для печати текущей страницы.

Ключ
Эти линии были удалены. Это слово было удалено.
Эти линии были добавлены. Это слово было добавлено.

Просмотр истории страницы


Есть 7 изменений. Просмотреть первое изменение .

 Вызов lower_bound:     
 {noformat}
  int pos = lower_bound(dict.begin(),
  dict.end(),
  make_pair(pref, 0))
  - dict.begin();
 {noformat}
 В pos находим (дихотомией) в отсортированном словаре пар dict 
 позицию слова пары со словом pref. 
 \\
  
 14_FebB. AUTO
 [http://dl.gsu.by/task.jsp?nid=1270623&cid=15]
  
 Идея решения, вводим словарь и по ходу заносим в вектор слова и номера этих слов в словаре.
 Сортируем слова по возрастанию (вместе с номерами).
 Цикл по поисковым префиксам 
    Вводим префикс и его позицию k
    Дихотомией (с помощью lower bound) 
      ищем в словаре pos первое вхождение префикса
    Инкрементируем pos на k 
    Если полученная позиция в словаре, 
         а слово на этой позиции совпадает с префиксом
      Тогда выводим её
      Иначе выводим \-1   
  
 Подробнее о коде
 {noformat}
       int pos = lower_bound(dict.begin(), 
                             dict.end(),
                             make_pair(pref, 0)) 
                 - dict.begin();
   int pos = lower_bound(dict.begin(),
 dict.end(),
 make_pair(pref, 0))
 - dict.begin();
 {noformat}
 В pos находим (дихотомией) в отсортированном словаре позицию слова pref. 
 {noformat}
      int poss = pos + k;
 &nbsp; &nbsp; &nbsp; if (poss < dict.size() && match(pref, dict\[poss\].first))
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;cout << dict\[poss\].second + 1 << endl;
 &nbsp; &nbsp; &nbsp; &nbsp; else cout << \-1 << endl;
  int poss = pos + k;
 if (poss < dict.size() && match(pref, dict[poss].first))
 cout << dict[poss].second + 1 << endl;
 else cout << -1 << endl;
 {noformat}
 если k-ое вхождение есть и соответствует pref,&nbsp;
 &nbsp; тогда выводим исходный номер слова
 &nbsp; иначе вводим \-1&nbsp;
 {noformat}
 bool match(string pref, string word)
&nbsp; {
 &nbsp; &nbsp; if (pref.size() > word.size()) return false;
 &nbsp; &nbsp; return word.substr(0, pref.size()) == pref;
 &nbsp; }
  {
 if (pref.size() > word.size()) return false;
 return word.substr(0, pref.size()) == pref;
 }
 {noformat}
 Соответствие слова из словаря word и искомого префикса pref
 Выясняется с помощю булевой функции match
  
 Далее приведен полный текст решения
 {code:title=all.cpp\|borderStyle=solid}
\#include <bits/stdc++.h>
  #include <bits/stdc++.h>
 using namespace std;
  
 int n, m;
 vector<pair<string, int> > dict;
  
 bool match(string& pref, string& word)
&nbsp; {
 &nbsp; &nbsp; if (pref.size() > word.size()) return false;
 &nbsp; &nbsp; return word.substr(0, pref.size()) == pref;
 &nbsp; }
  {
 if (pref.size() > word.size()) return false;
 return word.substr(0, pref.size()) == pref;
 }
  
int main()&nbsp;
  int main()
 {
 &nbsp; freopen("auto.in", "r", stdin);
 &nbsp; freopen("auto.out", "w", stdout);
 &nbsp; cin >> n >> m;
 &nbsp; for (int i = 0; i < n; i++)
 &nbsp; &nbsp; {
 &nbsp; &nbsp; &nbsp; string s;
 &nbsp; &nbsp; &nbsp; cin >> s;
 &nbsp; &nbsp; &nbsp; dict.push_back(make_pair(s, i));
 &nbsp; &nbsp; }
 &nbsp; sort(dict.begin(), dict.end());
 &nbsp; for (int i = 0; i < m; i++)
 &nbsp; &nbsp; {
 &nbsp; &nbsp; &nbsp; int k; string pref;
 &nbsp; &nbsp; &nbsp; cin >> k >> pref;
 &nbsp; &nbsp; &nbsp; k--;
 &nbsp; &nbsp; &nbsp; int pos = lower_bound(dict.begin(),&nbsp;
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dict.end(),
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; make_pair(pref, 0))&nbsp;
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; - dict.begin();
 &nbsp; &nbsp; &nbsp; int poss = pos + k;
 &nbsp; &nbsp; &nbsp; if (poss < dict.size() && match(pref, dict\[poss\].first))
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;cout << dict\[poss\].second + 1 << endl;
 &nbsp; &nbsp; &nbsp; &nbsp; else cout << \-1 << endl;
 &nbsp; &nbsp; }
  freopen("auto.in", "r", stdin);
 freopen("auto.out", "w", stdout);
 cin >> n >> m;
 for (int i = 0; i < n; i++)
 {
 string s;
 cin >> s;
 dict.push_back(make_pair(s, i));
 }
 sort(dict.begin(), dict.end());
 for (int i = 0; i < m; i++)
 {
 int k; string pref;
 cin >> k >> pref;
 k--;
  int pos = lower_bound(dict.begin(),
 dict.end(),
 make_pair(pref, 0))
 - dict.begin();
 int poss = pos + k;
 if (poss < dict.size() && match(pref, dict[poss].first))
 cout << dict[poss].second + 1 << endl;
 else cout << -1 << endl;
 }
 }
 {code}
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: http://www.atlassian.com/software/confluence Build:#2.6.1 916) - Ошибка/новая особенность - Свяжитесь с Администраторами