按题意要求逐个获取单词对应的位置即可,存于keypos中。如果直接查找,会超时。
#include <vector>
#include <map>
#include<algorithm>
#include<cmath>
#include<set>
#include <string>
#include<iostream>
#include<utility>
#include<unordered_map>
#include<cstring>
#include<sstream>
#include <iostream>
#include <string>
using namespace std;
void getindex(const vector<vector<string>>& dict,unordered_map<string, set<pair<int, int>>>&keypos)
{
int dictsize = dict.size();
for (int i=0;i<dictsize;++i)
{
int size2 = dict[i].size();
for (int j=0;j<size2;++j)
{
string tmp;
stringstream ss(dict[i][j].c_str());
while(ss>>tmp)
{
keypos[tmp].insert({i,j});
}
}
}
}
inline void tolower(string& s)
{
int size = s.size();
for (int i = 0; i < size; ++i)
{
if (isalpha(s[i]))
s[i] = tolower(s[i]);
else
s[i]=' ';
}
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int n;
cin >> n;
cin.get();
vector<vector<string>>origin(n);
vector<vector<string>>small(n);
for(int i=0;i<n;++i)
{
string textline;
while (getline(cin, textline) && textline != "**********")
{
origin[i].push_back(textline);
tolower(textline);
small[i].push_back(textline);
}
}
unordered_map<string, set<pair<int, int>>>keypos;
getindex(small,keypos);
int m;
cin >> m;
cin.get();
int cycle = m;
while (cycle-- > 0)
{
set<pair<int, int>>toprint;
string instruct;
int pos;
getline(cin, instruct);
if ((pos = instruct.find("AND")) != -1)
{
tolower(instruct);
string first = instruct.substr(0, pos - 1);
string second = instruct.substr(pos + 4);
set<pair<int, int>>s1(keypos[first]),s2(keypos[second]);
set<int>index1, index2, index;
for (auto elem : s1)
{
index1.insert(elem.first);
}
for (auto elem : s2)
{
index2.insert(elem.first);
}
set_intersection(index1.begin(), index1.end(), index2.begin(), index2.end(), inserter(index, index.begin()));
for(auto elem:s1)
{
if(index.find(elem.first)!=index.end())
toprint.insert(elem);
}
for(auto elem:s2)
{
if(index.find(elem.first)!=index.end())
toprint.insert(elem);
}
}
else if ((pos = instruct.find("OR")) != -1)
{
tolower(instruct);
string first = instruct.substr(0, pos - 1);
string second = instruct.substr(pos + 3);
set<pair<int, int>>s1(keypos[first]),s2(keypos[second]);
toprint.insert(s1.begin(), s1.end());
toprint.insert(s2.begin(), s2.end());
}
else if ((pos = instruct.find("NOT") != -1))
{
tolower(instruct);
string word=instruct.substr(4);
set<pair<int, int>>s1(keypos[word]);
set<int>in;
int cnt = 0;
for (auto elem : s1)
{
in.insert(elem.first);
}
for (int i = 0; i < n; ++i)
{
if (in.find(i) == in.end())
{
for (int j = 0; j < small[i].size(); ++j)
{
toprint.insert(make_pair(i, j));
}
}
}
}
else
{
tolower(instruct);
string word = instruct;
set<pair<int, int>>s(keypos[word]);
toprint.insert(s.begin(), s.end());
}
int cur = 0, pre = -1;
if (toprint.size() == 0)
{
cout << "Sorry, I found nothing.\n";
}
for (auto elem : toprint)
{
cur = elem.first;
if (cur!=pre&&pre!=-1)
cout << "----------\n";
cout << origin[elem.first][elem.second] << endl;
pre = cur;
}
cout << "==========\n";
}
}