大意略。
思路:首先开始写了一个STL,后来果断发现老是WA,为什么呢?后来手写了一个哈希,还是WA,然后发现,靠,原来还有空串,题目木有说呀。
/*哈希 0.752s*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <map>
using namespace std;
const int MAXSIZE = 10000003;
const int MAXN = 1510;
char A[MAXN][15], B[MAXN][15];
char st[MAXN*MAXN][30];
int first[MAXSIZE], next[MAXN*MAXN];
int n, m;
void init()
{
memset(first, -1, sizeof(first));
}
int ELFhash(char *key)
{
unsigned long h = 0;
while (*key)
{
h = (h<<4) + *key++;
unsigned long g = h & 0xf0000000L;
if (g) h^= g>>24;
h &= ~g;
}
return h % MAXSIZE;
}
int try_to_insert(int s)
{
int h = ELFhash(st[s]);
for(int v = first[h]; v != -1; v = next[v])
{
if(!strcmp(st[s], st[v])) return 0;
}
next[s] = first[h];
first[h] = s;
return 1;
}
void read_case()
{
init();
scanf("%d%d%*c", &n, &m);
for(int i = 0; i < n; i++) gets(A[i]);
for(int i = 0; i < m; i++) gets(B[i]);
}
void solve()
{
read_case();
int ans = 0, rear = 0;
for(int i = 0; i < n; i++)
{
char temp[30] = {'\0'};
for(int j = 0; j < m; j++)
{
strcpy(temp, A[i]);
strcat(temp, B[j]);
strcpy(st[rear], temp);
if(try_to_insert(rear)) { rear++; ans++;}
}
}
printf("%d\n", ans);
}
int main()
{
int T, times = 0;
scanf("%d%*c", &T);
while(T--)
{
printf("Case %d: ", ++times);
solve();
}
return 0;
}/*STL 2.476*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <map>
using namespace std;
const int MAXN = 1510;
map<string, int> Map;
char A[MAXN][15], B[MAXN][15];
int n, m;
void init()
{
Map.clear();
}
void read_case()
{
init();
scanf("%d%d%*c", &n, &m);
for(int i = 0; i < n; i++) gets(A[i]);
for(int i = 0; i < m; i++) gets(B[i]);
}
void solve()
{
read_case();
for(int i = 0; i < n; i++)
{
char temp[30] = {'\0'};
for(int j = 0; j < m; j++)
{
strcpy(temp, A[i]);
strcat(temp, B[j]);
if(!Map[temp]) Map[temp] = 1;
}
}
cout<<Map.size()<<endl;
}
int main()
{
int T, times = 0;
scanf("%d%*c", &T);
while(T--)
{
printf("Case %d: ", ++times);
solve();
}
return 0;
}
本文探讨了使用哈希和STL解决字符串匹配问题的方法,包括如何通过手写哈希函数来提高效率,并对比了不同实现方式的性能差异。

被折叠的 条评论
为什么被折叠?



