这题不难,只要有点 STL 的知识就行了
关于文章而言,肯定是每篇文章开个结构体去存
要存什么内容呢,我存了
每行是什么(每行的文本)
每行的字典(运用了例题5-3安妮字典中的初始化方法) (用 set)
//即使用 stringstream 读行内容,非常好用,
全篇文章的 字典(用 map)
以及所有文本的字典(map)
主要你要搞清楚你要用啥,刚开始不清楚没关系,写着写着,少什么加什么就行了
然后查询时 and 可以和 or 的情况整合一下下,少点代码 …
好,上代码,(注意不要少打或者多打‘-’!!!!!!’=‘) 不然就和我一样wa了呜呜呜
#include <bits/stdc++.h>
using namespace std;
const char *msg[]={"Sorry, I found nothing.","==========","----------"};
typedef set<string> Set;
map <string, int> exist; //全文
int ge;
struct stu{
vector <string> row; //行内容
vector <Set> dic; //行字典
map <string,int> you; //总文章字典
}web[110];
void input();
void query();
int main()
{
input(); //输入
query(); // 查询
return 0;
}
void input()
{
string s,buf; Set dyz;
scanf("%d",&ge); getchar();
for (int i = 0; i < ge; i++)
{
while(getline(cin,s))
{
dyz.clear();
if(s == "**********") break;
else web[i].row.push_back(s);
for (int i = 0; i < s.size(); i++)
{
if(isalpha(s[i])) s[i] = tolower(s[i]); else s[i] = ' ';
} // 标准化所存单词
stringstream ss(s);
while (ss >> buf)
{
dyz.insert(buf); web[i].you[buf] = 1;
exist[buf] = 1;
} //加全文单词,加行字典,加所有文本单词
web[i].dic.push_back(dyz); // 行字典搞完,放入
}
}
}
void query()
{
int q; string s,buf,s1,s2;
scanf("%d",&q); getchar();
while(q--)
{
getline(cin,s);
int n = s.size(),ok = 0,kefound = 1,f = 0; // f 表示找的到
for (int i = 0; i < n-3;i++)
{
if(s.substr(i,3) == "NOT") { ok = 3; break;
}
else if(s.substr(i,3) == "AND"){ ok = 1; break;
}
else if(s.substr(i,2) == "OR") { ok = 2; break;
}
}
if(!ok){ // 毫无花里胡哨的一个单词
if(exist[s]){
for (int i = 0; i < ge; i++)
{
if(!web[i].you[s]) continue; // 没发现目标
else {
if( f ) puts(msg[2]);
else f = 1;
int m = web[i].row.size();
for (int j = 0; j < m; j++)
{
if( web[i].dic[j].count(s) ) cout<<web[i].row[j]<<endl;
}
}
}
}
}
else if(ok == 1 || ok == 2){ //AND 或者 OR
stringstream ss{s}; ss >> s1 >> buf >> s2;
// cout << s1 <<" " <<s2 << endl;
for (int i = 0; i < ge; i++)
{
int pke = 0;
if(ok == 1 && web[i].you[s1] && web[i].you[s2]) pke = 1;
else if( ok == 2 && ( web[i].you[s1] || web[i].you[s2] )) pke = 1;
if(pke)
{
if(f) puts(msg[2]);
else f = 1;
int m = web[i].row.size();
for (int j = 0; j < m; j++)
{
if( web[i].dic[j].count(s1) || web[i].dic[j].count(s2) )
cout<<web[i].row[j]<<endl;
}
}
}
}
else{ // NOT
stringstream ss(s); ss >> buf; ss >> buf; // buf为该单词
// cout<<buf<<endl;
for (int i = 0; i < ge; i++)
{
if(!web[i].you[buf])
{
if(f) puts(msg[2]);
else f = 1;
int m = web[i].row.size();
for (int j = 0; j < m; j++)
{
cout<<web[i].row[j]<<endl;
}
}
}
} // 如果没找到
if(!f) puts(msg[0]); puts(msg[1]);
}
}