您的位置:首页 > 其它

poj 3349 Snowflake Snow Snowflakes (hash)

2017-01-17 19:54 337 查看
数据结构中学的hash没学好,也没怎么练,五子棋的hash算法部分就没看懂,也就没看,今天从头看下,发现hash算法非常有用,复杂度为1,如果知道数据的范围,储存和查询数据是不二选择,非常快,要把基础中的hash刷完,配合实战,做做hash算法

//1

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
const int mod= 33119;
int hash1[33119][250];//100003
int a[100009][7];
int main() {

int n;
scanf("%d",&n);
memset(hash1,0,sizeof(hash1));
int flag=1;
for(int i=1;i<=n;i++)
{
int cnt=0;
for(int j=1;j<=6;j++)
{
scanf("%d",&a[i][j]);
cnt+=a[i][j];
}
cnt%=mod;
sort(a[i]+1,a[i]+7);
hash1[cnt][0]++;
hash1[cnt][hash1[cnt][0]]=i;
for(int j=1;j<hash1[cnt][0];j++)
{
int k=1;
for(k=1;k<=6;k++)
if(a[hash1[cnt][j]][k]!=a[i][k])break;
if(k==7)flag=0;
}
}
if(flag==0)printf("Twin snowflakes found.\n");
else printf("No two snowflakes are alike.\n");
return 0;
}


//2

#include<stdio.h>
#include<string.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>

#include<iostream>
using namespace std;

#define NN 15000 // 14997 + 3
#define NL 100
#define L 6
typedef struct
{
int a[L];
}item;
item snow [NN][NL];
int m[NN];
int hash(item SNOW)
{
int key =0;
for(int i=0;i<6;i++)
key+=SNOW.a[i];
key %=14997;
return key;
}
int cmp(item x, item y){
int st, i, j;
for (st = 0; st < 6; st++){// ÓÒÒÆ
for (i = st, j = 0; j < 6; j++, i = (i + 1) % 6){
if(x.a[i] != y.a[j]) break;
}
if(j == 6) return 1;
}
for (st = 0; st < 6; st++){// ×óÒÆ
for (i = st, j = 0; j < 6; j++, i = (i + 5) % 6){
if(x.a[i] != y.a[j]) break;
}
if(j == 6) return 1;
}
return 0;
}

int main()
{int i, j, pos, n;
item SNOW;
scanf("%d", &n);
memset(m, 0, sizeof(m));
for (i = 1; i <= n; i++){
for (j = 0; j < 6; j++){
scanf("%d", &SNOW.a[j]);
}
pos =hash(SNOW);
for(j=0;j<m[pos];j++)
{
if(cmp(SNOW,snow[pos][j]))
{
puts("Twin snowflakes found.");
return 0;
}
}
snow[pos][m[pos]] = SNOW;
m[pos]++;

}
puts("No two snowflakes are alike.");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: