您的位置:首页 > 其它

UVA 1597 - Searching the Web

2017-07-07 17:43 423 查看
有点小坑,一定要注意利用bool* 来存储map的查询结果,这样一优化后就不会导致超时的问题了,不然每次都用map查询会大大降低时间的效率。

就是建立每一行文本中出现的每个单词与对应行的行号的映射,后面再对查询内容进行分析,逐行判断即可。源代码如下,很好理解。

#include<iostream>
#include<vector>
#include<string>
#include<type_traits>
#include<sstream>
#include<tuple>
#include<bitset>
#include<regex>
#include<set>
#include<stack>
#include<queue>
#include<map>
using namespace std;

typedef bool judge[1505];
int n, m;
map<string, judge> str2jud;
int edge[105];
string document[1505];

void explain(string read,int line){
string::iterator it = read.begin();
for (; it != read.end(); it++){
if (isalpha(*it)) *it = tolower(*it);
else *it = ' ';
}
stringstream ss(read);
string word;
while (ss >> word){
str2jud[word][line] = true;
}
}

int main(){
scanf("%d ",&n);
string del;
//getline(cin, del);
int lines = 0;
for (int i = 0; i < n; i++){
string read;
edge[i] = lines;
while (getline(cin, document[lines])){
if (document[lines]== "**********") break;
explain(document[lines],lines);
lines++;
}
}
edge
= lines;
int m;
scanf("%d ",&m);
//getline(cin,del);
for (int t = 0; t < m; t++){
string deal;
getline(cin, deal);
judge arr;
memset(arr,false,sizeof(arr));
bool *A, *B;
if (deal[0] == 'N'){
string word = deal.substr(4);
A = str2jud[word];
for (int i = 0; i < n; i++){
bool flag = true;
for (int j = edge[i]; j < edge[i + 1]; j++){
if (A[j]){
flag = false;
break;
}
}
for (int j = edge[i]; j < edge[i + 1]; j++) arr[j] = flag;
}
}
else if (deal.find("AND") != string::npos){
int pos = deal.find("AND");
string word1 = deal.substr(0,pos-1);
string word2 = deal.substr(pos+4);
A = str2jud[word1];
B = str2jud[word2];
for (int i = 0; i < n; i++){
bool flag1 = false;
bool flag2 = false;
for (int j = edge[i]; j < edge[i + 1]; j++){
if (A[j] == true) flag1 = true;
if (B[j] == true) flag2 = true;
if (flag1&&flag2) break;
}
if (flag1&&flag2){
for (int j = edge[i]; j < edge[i + 1]; j++){
if (A[j] == true || B[j] == true) {
arr[j] = true;
}
}
}
}
}
else if (deal.find("OR")!=string::npos){
int pos = deal.find("OR");
string word1 = deal.substr(0,pos-1);
string word2 = deal.substr(pos+3);
A = str2jud[word1];
B = str2jud[word2];
for (int i = 0; i < n; i++){
bool flag = false;
for (int j = edge[i]; j < edge[i + 1]; j++){
if (A[j]||B[j]){
arr[j] = true;
}
}
}
}
else{
A = str2jud[deal];
for (int i = 0; i < n; i++){
for (int j = edge[i]; j < edge[i + 1]; j++){
if (A[j]==true) arr[j]=true;
}
}
}
bool before = false;
bool flag = false;
bool output = false;
for (int i = 0; i < n; i++){
for (int j = edge[i]; j < edge[i + 1]; j++){
if (arr[j]==true){
if (before){
cout << "----------\n";
before = false;
}
flag = true;
cout << document[j] << "\n";
output = true;
}
}
if (output){
before = true;
output = false;
}
}
if (!flag) cout << "Sorry, I found nothing.\n" ;
cout << "==========\n";
}
//system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: