HDU 1277 (full text search)

This problem using the map data structure, you can search violence. First, the digital information stored text, the keywords and the keyword number information into the structure, the first four digits and the corresponding key information stored in the keyword number Map; front to back and then search the full text of the digital information, if the text the first four digits for four consecutive numbers and a keyword message is the same, the subsequent character of the two is more, if all the same, then the match is successful, the output keyword number; otherwise, continue to search the full text from the original position back, until the search full text.

#include <iostream>
#include <string>
#include <map>
using namespace std;
const int MAXN = 10005;
 
struct keyword //关键字
{
	int num; //序号
	string message; //信息
}key[MAXN];
 
int main()
{
	int M, N; //数字信息行数,关键字个数
	string full; //数字信息全文
	string temp; //每次读一行
	map<string, int> mp; //关键字信息的前4个数字-关键字序号
 
	while (cin >> M >> N)
	{
		full = ""; //清空上个测试用例的全文
		mp.erase(mp.begin(), mp.end()); //清空map
		for (int i = 0; i < M; i++) //读入全文
		{
			cin >> temp;
			full += temp;
		}
		//读入关键字序号和信息,并将关键字信息的前4个数字和关键字序号存入map
		for (int i = 1; i <= N; i++)
		{
			cin >> temp >> temp >> temp >> key[i].message; //前三个temp读取[Key No. i]
			key[i].num = i;
			mp[key[i].message.substr(0, 4)] = key[i].num;
		}
 
		int total = 0; //查找到的关键字的数量
		int len = full.size(); //全文字符数
		for (int i = 0; i <= len - 4; i++) //从前到后依次查找
		{
			//全文中从第i个位置开始的4个字符在map中是否存在
			if (mp.find(full.substr(i, 4)) != mp.end())
			{
				string nowKey = key[mp[full.substr(i, 4)]].message; //关键字信息
				int nowLen = nowKey.size(); //关键字信息长度
				bool flag = true; //关键字和全文后续字符是否匹配
				int j, k;
				//对关键字和全文的后续字符依次匹配
				for (j = i + 4, k = 4; j < len && k < nowLen; j++, k++)
				{
					if (full[j] != nowKey[k]) //对应字符不同,匹配失败
						flag = false;
				}
				if (flag == true && k == nowLen) //匹配成功
				{
					++total;
					if (total == 1)
						cout << "Found key:";
					cout << " [Key No. " << key[mp[full.substr(i, 4)]].num << "]";
					mp.erase(full.substr(i, 4)); //清楚该关键字,避免重复输出
				}
			}
		}
		if (total == 0) //没有查找到任何关键字
			cout << "No key can be found!";
		cout << endl;
	}
	return 0;
}

Keep up.

Published 206 original articles · won praise 1 · views 8986

Guess you like

Origin blog.csdn.net/Intelligence1028/article/details/104838649