本文主要是介绍习题5-10 在Web中搜索(Searching theWeb,ACM/ICPC Beijing 2004,UVa1597),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原题链接:https://vjudge.net/problem/UVA-1597
分类:STL综合
备注:中级模拟
前言:题目真的不难,但是我的代码做不出我想要的结果。debug好久才发现自己踩了个STL的坑!我用了map<string,set<int> >来记录每个单词在段落的哪些行出现过,本来如果map里面没有这个string时map.count(string)为假,但是如果做出map[string].count(int)的操作,map里面就有了这个string,变成map.count(string)为真!
这次用了许多STL的新搭配,还算是有收获吧。
代码如下:
#include<iostream>
#include<sstream>
#include<vector>
#include<string>
#include<cctype>
#include<map>
#include<set>
using namespace std;
const int maxn = 100 + 5;
int N, M, judge;
vector<string>doc[maxn];
map<string, set<int> >zhao[maxn];
void output1(string x)
{set<int>prag;for (int i = 0; i < N; i++)if (zhao[i].count(x))prag.insert(i);for (set<int>::iterator it = prag.begin(); it != prag.end(); ++it){judge = 1;if (it != prag.begin())cout << "----------\n";for (int i = 0; i < doc[*it].size(); i++)if (zhao[*it][x].count(i))cout << doc[*it][i] << "\n";}
}
void output2(string s, int pos, int pos2)
{string x1 = s.substr(0, pos), x2 = s.substr(pos2 + 1, s.length() - pos2 - 1);set<int>prag;if (s[pos + 1] == 'O') { for (int i = 0; i < N; i++)if (zhao[i].count(x1) || zhao[i].count(x2))prag.insert(i); }else { for (int i = 0; i < N; i++)if (zhao[i].count(x1) && zhao[i].count(x2))prag.insert(i); }for (set<int>::iterator it = prag.begin(); it != prag.end(); ++it){judge = 1;if (it != prag.begin())cout << "----------\n";for (int i = 0; i < doc[*it].size(); i++)if ((zhao[*it].count(x1) && zhao[*it][x1].count(i)) || (zhao[*it].count(x2) && zhao[*it][x2].count(i)))cout << doc[*it][i] << "\n";}
}
void output3(string s, int pos)
{string x = s.substr(pos + 1, s.length() - pos - 1);set<int>prag;for (int i = 0; i < N; i++)if (!zhao[i].count(x))prag.insert(i);for (set<int>::iterator it = prag.begin(); it != prag.end(); ++it){judge = 1;if (it != prag.begin())cout << "----------\n";for (int i = 0; i < doc[*it].size(); i++)cout << doc[*it][i] << "\n";}
}
int main(void)
{cin >> N; getchar();string s;for (int i = 0; i < N; i++){while (getline(cin, s)){if (s[0] == '*')break;doc[i].push_back(s);for (int j = 0; j < s.length(); j++)if (!isalpha(s[j]))s[j] = ' ';else s[j] = tolower(s[j]);stringstream ss(s);string x;while (ss >> x)zhao[i][x].insert(doc[i].size() - 1);}}cin >> M; getchar();while (M--){judge = 0;getline(cin, s);int pos = s.find(' ', 0);if (pos == string::npos)output1(s);else{int pos2 = s.find(' ', pos + 1);if (pos2 != string::npos)output2(s, pos, pos2);else output3(s, pos);}if (!judge)cout << "Sorry, I found nothing.\n";cout << "==========\n";}return 0;
}
这篇关于习题5-10 在Web中搜索(Searching theWeb,ACM/ICPC Beijing 2004,UVa1597)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!