poj 3349 Snowflake Snow Snowflakes (hash)

来源:互联网 发布:海通证券行情软件 编辑:程序博客网 时间:2024/05/29 07:45

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

#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;}

0 0
原创粉丝点击