1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
// For a list of strings, there will be several queries of the form "i p".
// Examine list[0..i-1] against p to find all strings with maximum common prefix with p.
// Return the lexicographic min of these strings.
//
// More details on input/output
// https://www.codechef.com/JUNE18B/problems/SHKSTR
using namespace std;
bool IsPrefix(const string& p, const string& s)
{
return p.size()<=s.size() &&
equal(p.begin(), p.begin()+p.size(), s.begin());
}
void QuerySearch(const map<string,int>& m, int index, const string& prefix)
{
int psize = prefix.size();
bool next_prefix;
string p;
while (psize--)
{
// Keep chopping last character
p.assign(prefix, 0, psize+1);
next_prefix = false;
//cout << " p: "<< p << endl;
auto it = m.lower_bound(p);
if (it != m.end())
{
//cout << " iterator currently set at word "<<it->first<< endl;
// Position was beyond scope of index, but answer should be nearby
while (it->second >= index)
{
++it;
if (it==m.end())
{
next_prefix = true;
break;
}
}
if (next_prefix)
continue;
if (IsPrefix(p, it->first))
{
cout << it->first << endl;
//cout << it->first << " " << it->second << endl;
return;
}
}
}
// Possible default response if not even one letter matches
//cout << "----" << endl;
}
void Show(const pair<string,int>& kv)
{
cout << kv.first << " => " << kv.second << endl;
}
void Show(const map<string,int>& m)
{
for (auto& kv : m)
Show(kv);
cout << endl;
}
int main()
{
// Ordered map so that it's inherently sorted but remembers its real "index"
map<string,int> m
{
{"abcd",0},
{"abce",1},
{"abcdex",2},
{"abcde",3},
{"atttttack", 4},
{"atttttend", 5},
{"atttttention", 6},
{"atttttraction", 7},
};
cout << "Ordered Map:\n";
Show(m);
vector<pair<int,string>> queries
{
{3, "abcy"},
{3, "abcde"},
{4, "abcde"},
{9, "atttttf"},
{9, "atttttel"},
{4, "atttttf"},
{5, "atttttel"},
};
cout << "Queries and Responses:\n\n";
for (auto& query : queries)
{
cout << "{" << query.first << ", " << query.second << "}\n";
QuerySearch(m, query.first, query.second);
cout << endl;
}
return 0;
}
| |