poj 3349 字符串hash

poj 3349 Snowflake Snow Snowflakes

题意:
   给你N个雪花的描述,问你在这些雪花中用没有相同的雪花。
分析:
 1,由于hash的雪花数量较多,这里用求和取模hash
 2,把每个雪花按顺时针和逆时针进行hash 处理,用拉链法处理冲突。
代码:
unsigned int BKDRHash(char*str)   
{   
    unsigned int seed=131 ;// 31 131 1313 13131 131313 etc..    
    unsigned int hash=0 ;   

    while(*str)   
    {   
        hash=hash*seed+(*str++);   
    }   

    return(hash % maxn);   
}   

const int N = 1200010;
const int H = 1200007;

struct Node
{
    int num[6];
    int next;
};
Node node[N];
int cur;
int hashTable[H];

void initHash()
{
    cur = 0;
    for (int i = 0; i < H; ++i) hashTable[i] = -1;
}

unsigned int getHash(int* num)
{
    unsigned int hash = 0;
    for (int i = 0; i < 6; ++i)
    {
        hash += num[i];
    }
    return hash % H;
}

bool cmp(int* num1, int* num2)
{
    for (int i = 0; i < 6; ++i)
    {
        if (num1[i] != num2[i]) return false;
    }
    return true;
}

void insertHash(int* num, unsigned int h)
{
    for (int i = 0; i < 6; ++i) node[cur].num[i] = num[i];
    node[cur].next = hashTable[h];
    hashTable[h] = cur;
    ++cur;
}

bool searchHash(int* num)
{
    unsigned h = getHash(num);
    int next = hashTable[h];
    while (next != -1)
    {
        if (cmp(num, node[next].num)) return true;
        next = node[next].next;
    }
    insertHash(num, h);
    return false;
}

int main()
{
     #ifndef ONLINE_JUDGE
     intxt;outtxt;
     #endif // ONLINE_JUDGE
    int num[2][12];
    int n;
    bool twin = false;
    initHash();
    scanf("%d", &n);
    while (n--)
    {
        for (int i = 0; i < 6; ++i) 
        {
            scanf("%d", &num[0][i]);
            num[0][i + 6] = num[0][i];
        }
        if (twin) continue;
        for (int i = 0; i < 6; ++i)
        {
            num[1][i + 6] = num[1][i] = num[0][5 - i];
        }
        for (int i = 0; i < 6; ++i) 
        {
            if (searchHash(num[0] + i) || searchHash(num[1] + i))
            {
                twin = true;
                break;
            }
        }
    }
    if (twin) printf("Twin snowflakes found.\n");
    else printf("No two snowflakes are alike.\n");
    return 0;
}

你可能感兴趣的:(ACM->字符串)