HDU 1251:统计难题

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

题意不难理解,就是先输入不知道多少个字符串,然后用一个空行结束这个输入,然后接下来不知道多少行再输入一些字符串,询问上面输入的字符串中,以该字符串为前缀的字符串的个数。

但是实现起来并不简单,首先要考虑如何输入(让第一部分的字符串在输入空行之后停止读入),然后还要考虑如何用map来标记前缀的个数。

实现:用gets()读入字符串(不能用cin>>,因为cin>>不接收空行),当某个字符串的长度为0的时候,即表示该字符串为空行,第一部分读入完毕。每次读入一个字符串,用map来记录这个字符串中从长度为1~l的字符串的个数(从后往前记录,先记录完整的字符串,然后把最后一位变成'',以此类推)。最后依次输入需要询问的字符串,输出出现的次数就可以了

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <string>
#define ll long long
#define ms(a) memset(a,0,sizeof(a))
#define pi acos(-1.0)
#define INF 0x3f3f3f3f
const double E=exp(1);
const int maxn=1e6+10;
using namespace std;
int main(int argc, char const *argv[])
{
	char ch[20];
	map<string,int>mmp;
	int flag=0;
	while(gets(ch))
	{
		int l=strlen(ch);
		if(l==0)
		{
			flag++;
			break;
		}
		for(int i=l;i>0;i--)
		{
			ch[i]='';
			mmp[ch]++;
		}
	}
	string s;
	while(cin>>s)
	{
		cout<<mmp[s]<<endl;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Friends-A/p/10324451.html