POJ3349

Hash table经典算法

以前写的算法, 用时1860ms

 

#include <iostream>
#include <string>

using namespace std;

#define HASHLEN 202099
#define SNOWNUM 100001

struct Node {
    int arms[6];
    int next;
};

Node snow[SNOWNUM];
int hashTable[HASHLEN];

bool cmp(int *armsx, int *armsy){
    int i, j;
    for (i = 0; i < 6; i++) {
        for (j = 0; j < 6; j++) {
            if (armsx[j] != armsy[(i+j)%6])
                break;
        }
        if (j == 6) return true;
    }

    for (i = 0; i < 6; i++) {
        for (j = 0; j < 6; j++) {
            if (armsx[j] != armsy[(6+i-j)%6])
                break;
        }
        if (j == 6) return true;
    }

    return false;
}

int main()
{
    int n, cnt, hVal, idx, pre, i, j;

    scanf("%d",&n);

    memset(hashTable, 0x00, sizeof(hashTable));

    for (i = 1; i <= n; i++)
    {
        cnt = 0;
        //input data
        snow[i].next = 0;
        for (j = 0; j < 6; j++) {
            scanf("%d",&snow[i].arms[j]);
            cnt += snow[i].arms[j];
        }

        //calc hash key
        hVal = cnt % HASHLEN;

        //insert to hashtable
        idx = hashTable[hVal];
        if (idx > 0) {
            do {
                pre = idx;
                //Compare same snowflake
                if (cmp(snow[i].arms, snow[pre].arms)) {
                    cout << "Twin snowflakes found." << endl;
                    return 0;
                }
                idx = snow[idx].next;
            } while (idx > 0);
            snow[pre].next = i;
        } else {
            hashTable[hVal] = i;
        }
    }

    cout << "No two snowflakes are alike." << endl;

    return 0;
}

 

posted @ 2017-01-03 13:51  Jim'sBlog  阅读(248)  评论(0编辑  收藏  举报