您的位置:首页 > 其它

HDOJ1251(前缀匹配---分块查找&map应用)

2015-08-04 17:00 253 查看
分块查找算法

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int SIZE=1300000+16;
const int BLOCKS=50000; //块的大小
char word[SIZE][11];
char pre[20];
int Num[27];
bool isPre(char mo[],char so[])
{
int i=0,j=0;
while(mo[i]&&so[j])
{
if(mo[i]!=so[j])
return false;
i++;
j++;
}
if(so[j]=='\0')
return true;
return false;
}
int main()
{
int cnt=0;
char fin[11]={'\0'};
while(gets(fin))
{
if(fin[0]=='\0')
break;
int key=fin[0]-'a';
int pos=key*BLOCKS+Num[key];
Num[key]++;
strcpy(word[pos],fin);
}

while(scanf("%s",pre)!=EOF)
{
int num=0;

int key=(pre[0]-'a');
int start=key*BLOCKS;

for(int i=start;i<start+Num[key];i++)
{
if(isPre(word[i],pre))
num++;
}

printf("%d\n",num);
}

return 0;
}


利用STL库中的map解决

#include<iostream>
#include<cstdio>
#include<string>
#include<map>
using namespace std;
map<string, int> word;
int main()
{
string x="";
while(true)
{
char a;
scanf("%c",&a);
if(a=='\n')
{
scanf("%c",&a);
x="";
}
if(a=='\n')
break;
x+=a;
word[x]++;
}

string pre;
while(cin>>pre)
{
cout<<word[pre]<<endl;
}
//感受到STL的威力了么
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: