题目链接:UVa 10887 - Concatenation of Languages
这题目最后看了GooMaple的代码才AC了,还是有几个疑问。
1、为什么用cin读串不行,用gets可以,题目说了字符是从'a'~'z'的,没有空格的话我认为用哪个读都是一样的。
2、为什么hash那块需要保证是正数,sum怎么算也应该不是负数。
希望有大神可以指点一二。
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
const int MAX_N = 1500 * 1500 + 100;
const int MAX_M = 10 + 5;
const int HASH_CODE = 177;
char A[1505][MAX_M];
char B[1505][MAX_M];
int next[MAX_N];
int head[MAX_N];
char uni[MAX_N][MAX_M * 2];
int T,M,N;
int cnt;
int hash(char *str)
{
int sum = 0;
while(*str)
{
sum = sum * HASH_CODE + *str;
str++;
}
return (sum & 0x7FFFFFFF) % MAX_N;//确保是正数
}
void try_to_insert(int s)
{
int h = hash(uni[s]);
int u = head[h];
while(u)
{
if(!strcmp(uni[u],uni[s]))
return ;//找到了,插入失败
u = next[u];
}
next[s] = head[h];
head[h] = s;
cnt++;
}
int main()
{
cin>>T;
int num = 0;
while(T--)
{
memset(head, 0, sizeof(head));
cnt = 1;
cin>>M>>N;
int i,j;
getchar();//吸回车
for(i = 0;i < M;i++)
gets(A[i]);
for(i = 0;i < N;i++)
gets(B[i]);
for(i = 0;i < M;i++)
for(j = 0;j < N;j++)
{
sprintf(uni[cnt],"%s%s", A[i], B[j]);
try_to_insert(cnt);
}
cout<<"Case "<<++num<<": "<<cnt - 1<<endl;
}
}