第一道题学习哈希。
原解博客http://blog.csdn.net/alongela/article/details/8245005
边看边思考,个人的理解是,哈希将一串数字的某种特征提取出来,比如本题,提取出的特征是和取模, 只有具有相同的和取模的字符串才进行比较,节省了大量无用的比较,如果暴力,那么每两个字符串都将比较一次,O(n^2)加上这么大的数据量是要TLE的。而哈希将比较缩短到一个小范围内
#include<iostream>
#include <string>
#include<algorithm>
#include<fstream>
#include<cmath>
using namespace std;
#define lch(i) ((i)<<1)
#define rch(i) ((i)<<1|1)
#define sqr(i) ((i)*(i))
#define pii pair<int,int>
#define mp make_pair
#define FOR(i,b,e) for(int i=b;i<=e;i++)
#define FORE(i,b,e) for(int i=b;i>=e;i--)
#define ms(a) memset(a,0,sizeof(a))
const int maxnum =1200007;
const int INF = 1000000000;
int tol,n,m,newn;
struct node
{
int num[6],next;
}h[maxnum];
int counth=0;
int hashtable[maxnum];
void InitHashTable(){
FOR(i,1,maxnum) hashtable[i]=-1;
}
bool cmp(int* num1,int* num2){
FOR(i,0,5){
if(num1[i]!=num2[i])return false;
}
return true;
}
void InsertHash(int *num,int hashsum){
h[counth].next=hashtable[hashsum];
FOR(i,0,5){
h[counth].num[i]=num[i];
}
hashtable[hashsum]=counth++;
}
bool SearchHash(int* num){
int sum=0;
FOR(i,0,5){
sum+=num[i];
}
sum%=maxnum;
int ptr=hashtable[sum];
while(ptr!=-1){
if(cmp(num,h[ptr].num)) return true;
ptr=h[ptr].next;
}
InsertHash(num,sum);
return false;
}
int main()
{
/*fstream fin("G:/1.txt");
fin>>m;*/
scanf("%d",&n);
int tmp[2][12],found=0;
InitHashTable();
FOR(i,1,n){
FOR(j,0,5){
scanf("%d",&tmp[0][j]);
tmp[0][j+6]=tmp[0][j];
}
if(found)continue;
FOR(j,0,5){
tmp[1][j]=tmp[1][j+6]=tmp[0][5-j];
}
FOR(j,0,5){
if(SearchHash(tmp[0]+j)||SearchHash(tmp[1]+j)){
found =1;
break;
}
}
}
if(found)printf("Twin snowflakes found.\n");
else printf("No two snowflakes are alike.\n");
return 0;
}