思路:感觉像是一道模拟题,把每行句子记录,然后把单词提取出来,存入Set里面。找的时候只需要找哪一段存在或者不存在这个单词,然后再逐行进行判断输出即可。
AC代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<cctype>
#include<algorithm>
#include<set>
#include<sstream>
#include<fstream>
using namespace std;
string raw[1510][85];
set<string> word[1510][1000]; //代表每一段每一行单词的集合
set<string> words[1510];//每一段单词的集合
int n,len[1510]; //len表示每一段的行数
ofstream SaveFile("output.txt");
void AND(string a,string b)
{
int i,j,f3 = 0; //f3的作用是控制输出格式
for(i = 0;i < n;i++)
{
if(words[i].count(a) && words[i].count(b))
{
if(f3 == 1)
{
printf("----------\n");
}
for(j = 0;j < len[i];j++)
{
if(word[i][j].count(a) || word[i][j].count(b))
{
cout << raw[i][j] << endl;
f3 = 1;
}
}
}
}
if(f3 == 0)
{
printf("Sorry, I found nothing.\n");
}
printf("==========\n");
}
void OR(string a,string b)
{
int i,j,f3 = 0;
for(i = 0;i < n;i++)
{
if(words[i].count(a) || words[i].count(b))
{
if(f3 == 1)
{
printf("----------\n");
f3 = 0;
}
for(j = 0;j < len[i];j++)
{
if(word[i][j].count(a) || word[i][j].count(b))
{
cout << raw[i][j] << endl;
f3 = 1;
}
}
}
}
if(f3 == 0)
{
printf("Sorry, I found nothing.\n");
}
printf("==========\n");
}
void NOT(string a)
{
int i,j,f3 = 0;
for(i = 0;i < n;i++)
{
if(!words[i].count(a))
{
if(f3 == 1)
{
printf("----------\n");
}
for(j = 0;j < len[i];j++)
{
cout << raw[i][j] << endl;
}
f3 = 1;
}
}
if(f3 == 0)
{
printf("Sorry, I found nothing.\n");
}
printf("==========\n");
}
int main()
{
string s,w;
int i,j,k,m;
scanf("%d",&n);
getchar();
memset(len,0,sizeof(len));
for(i = 0;i < n;i++)
{
j = 0;
while(getline(cin,s) && s[0] != '*')
{
raw[i][j] += s;
for(k = 0;k < s.length();k++)
{
if(!isalpha(s[k]))
{
s[k] = ' '; //把非字母以外的其他东西都转换成空格
}
}
transform(s.begin(),s.end(),s.begin(),::tolower); //全部转换为小写
stringstream ss(s);
while(ss >> w)
{
word[i][j].insert(w);
words[i].insert(w);
}
j++;
}
len[i] = j;
}
scanf("%d",&m);
getchar();
while(m--)
{
string a,b,ww;
getline(cin,ww);
for(i = 0;i < ww.length();i++)
{
if(ww[i] == 'A')
{
AND(ww.substr(0,ww.find_first_of("A")-1),ww.substr(ww.find_first_of("A")+4));
break;
}
else if(ww[i] == 'R')
{
OR(ww.substr(0,ww.find_first_of("R")-2),ww.substr(ww.find_first_of("R")+2));
break;
}
else if(ww[i] == 'T')
{
NOT(ww.substr(ww.find_first_of("T")+2));
break;
}
}
if(i == ww.length())
{
int f1 = 0;
for(i = 0;i < n;i++)
{
if(words[i].count(ww))
{
if(f1 == 1)
{
printf("----------\n");
}
for(j = 0;j < len[i];j++)
{
if(word[i][j].count(ww))
{
cout << raw[i][j] << endl;
f1 = 1;
}
}
}
}
if(f1 == 0)
{
printf("Sorry, I found nothing.\n");
}
printf("==========\n");
}
}
}